1. What is cocoa? Cocoa is a toolkit written in OC language, which has a large number of libraries and structs, which is actually equivalent to standard APIs in Java and standard libraries in C + +. There is no concept of namespaces in OC, so prefixes are used to prevent naming collisions, so you will see a large number of NS-prefixed class names, structs, enumerations, and so on.
2, the cocoa Framework consists of the foundation Kit, APP Kit two parts, the former is the basic tool library, the latter is mainly UI library, advanced objects and so on.
3, the static identity of the class variable is defined outside the interface, class variables can only be accessed by this class, unless the class method is provided to provide external access to this class variable.
4, @ grammar is a special type of the OC syntax, C is not.
5, OC only the member variables of the class has access control, @public, @protected, @private, the default is @protected, class variables, class methods, member methods are not access modifiers, all methods are public, All class variables are private.
6, OC class method can only be called class, if the use of object calls will be error, and Java is just a warning.
7, the definition of the class in OC @interface and Java interface is not the same thing, OC @protocol and Java interface is matter. @interface is similar to the Java and C + + class keywords, in OC and C + +, are used to write the class definition in the header file, and Java has no header file concept, as for why there is such a difference, I think it is for OC and C + + compiler convenient, Most of the time, the compiler just needs to know the definition of the header file class to know what the properties and methods of this class are.
8, Get prefix method has special meaning in OC, so try to use member variable name as the function name of getter method.
9, OC is a dynamic language, So even if the @interface is not defined in the. m file is also OK, generally we are to provide others with a header file, this situation is equivalent to the method of privatization, for me like in the process of writing code at any time Add method but do not want to move the head file is still relatively cool.
10. All objects in OC are accessed using pointers, C + + references, no in OC, I'd rather you forced me to use a method, than you offered me two ways I don't know which method to use well.
11, OC method definition and invocation is a big "feature":
Method Name: (parameter 1 type) parameter 1 variable parameter 2 tag: (parameter 2 type) parameter 2 variable,:-(return type.
[Class or instance pointer method name: Parameter 1 label 2: Parameter 2 ...],
In order to look good, the first parameter is generally not tagged name, of course, the tag names can be hidden, but not recommended, because when you take over a departing person program, where the Java program calls a method with five or more parameters, but you do not have this method of the API, Then it's hard to guess what the five parameters are all about, but when Objective-c calls, each parameter must have a method tag name in front of it, so you can easily see what this parameter means from the tag name.
12. Call the class method:
[Fraction t];
[[Fraction class] t];
Class Clazz=[fraction class]; [Clazz T];
Class comes from NSObject, which is equivalent to the GetClass () method in Java, which is to get the class object
Clazz is not in front of *, this is because class is already a pointer. Another way of nesting calls, you have to learn
This is no different from a.b () c () in Java.
There are several ways to get class:
[Class or Object class]
[Class or Object Superclasss]
Nsclassfromstring (string form of class name)
You can also convert a class to a string form by using the following function:
Nsstringfromclass (Class)
13, OC in the best display of custom class inheritance NSObject, you can get Alloc, init, release and other methods.
14, the use of nil in OC for NULL, but with the null in Java is still different, Java calls null method, will report the infamous null pointer exception, and OC will not, so in OC you no longer have to worry about null pointers.
15, Cocoa provides many functions and Java in the API is very different, Java is purely object-oriented, all methods must be defined in the class, but OC is compatible with the C language, so C in the process-oriented thinking in OC is also good, so cocoa many things are not objects , but the functions and structures of the C language, such as NSLog ().
16. Initialization of objects
Before we see that the most instantiated object is: Fraction *frac=[[fraction alloc] init];
This is not the same as Java, Java object creation requires only new, and the constructor method is called (in fact, the virtual machine plane is divided into two steps: The new object, the execution <init> method (including the constructor method)), but OC is divided into two steps: allocating memory (while assigning the variable initial value), Initialization
(1), Alloc is a class method inherited from the NSObject, used to allocate storage space for the object, all member variables at this time to determine their own memory location, and is assigned the initial value, the integer type is 0, the floating-point number is 0.0,bool No, the object type is Nil,alloc method returns a pointer to an object.
(2), init This method is inherited from NSObject, you can overwrite it, of course, Init is not a construction method, just a common method, you can even switch to other methods, but we are accustomed to the method name prefix plus init.
Remember that the constructor method in Java does not return a value, so in order to achieve Java this effect: Test t = new Test (2), OC requires you to manually in the ordinary method (equivalent to the construction method) return self.
17. The description method in NSObject corresponds to the ToString method of object in Java, which is used to get the string representation of an object. The only difference is that you need to use the formatted string%@ in OC to trigger description to be called:
Fraction *frac=[[fraction alloc] init];
NSLog (@ "%@", frac);
18, Objective-c's exception all inherit from NSException, of course NSException itself also inherits from NSObject. Use the following block of statements for exception trapping:
@try {
< #statements #>
}
@catch (NSException *exception) {
< #handler #>
}
@finally {
< #statements #>
}
In general, the exception system in OC is similar to the exception system in Java, the only difference is that there is a business exception in Java, meaning that you have to catch him, if you do not catch a compilation error, the exception in OC is basically a runtime exception in Java, if you do not capture, The exception program crashes and is especially important in some cyclic batch tasks.
18, OC also has a feature that is his weak type ID, he can represent any object, in fact, it should be the use of the universal pointer address, because the Operation object in OC must be a pointer, and the pointer itself is a string of addresses, so through the pointer can point to all different objects.
19, inheritance (feel and Java almost AH)
20, reflection (this is the same as the anomaly, feel like Java also)
21, selector (actually is the function pointer in C, and the method class in Java)
22. Category, expand the functionality of the class, but you cannot declare a new member variable.
Categories are widely used, such as: third-party OBJECTIVE-C library Regexkitlite is the category of NSString, nsmutablestring, for the objective-c character type to increase the function of regular expressions.
23, the agreement @protocol, this is said earlier, the equivalent of Java interface, the idea is a kind of convention, norms, but the specific syntax is not the same.
24, finally to the memory management, wipe, not how to read, to find a special topic to understand.
25. String
-(BOOL) isequaltostring: (nsstring*) s
Compare two strings for equality, where Java is the same as = = Compare pointers and use the equal method to compare objects.
-(nsmutablestring*) appendString: (nsstring*) s
This is no different from Java's stringbuffer append.
26. Arrays
Cocoa uses Nsarray to represent an array, but it cannot store basic data types, enums, structs, nil, only objects that are objective-c.
Nsarray *array=[nsarray arraywithobjects: @ "One", @ "one", @ "three", nil];
As can be seen from the definition of this class method arraywithobjects, it uses nil to represent the end of an array element, which is why nil cannot be stored in Nsarray.
Nsmutablearray is a variable-length array, equivalent to a list in Java:
Nsmutablearray *marray=[nsmutablearray Arraywithcapacity:10];
[Marray AddObject: @ "Apple"];//adding array elements
Nsenumerator *e = [Marray objectenumerator];//gets an iterator to the array, equivalent to the iterator,reserveobjectenumerator in Java used to get the inverted array iterator. What's consistent with Java is that when you use iterators, you cannot add or delete operations to an array.
For (NSString *ms in Marray) {
NSLog (@ "%@", MS);
}
For-each is quickly enumerated as a new feature of Objective-c 2.0, which is not supported on Windows GNUstep.
27. Dictionary (hash table)
Nsdictionary is used to store the data structure of the key-value, similar to the map in Java.
Nsdictionary *dic=[nsdictionary Dictionarywithobjectsandkeys: @ "Apple", @ "A", @ "Google", @ "G", nil];// Variable parameters after Dictionarywithobjectandkeys, each of the two is a value-key, ending with nil.
NSLog (@ "%@", [dic Objectforkey: @ "A"]);//query value by specified key
Similarly, there are nsmutabledictionary that represent a variable length dictionary.
Nsmutabledictionary *mdic=[nsmutabledictionary Dictionarywithcapacity:10];
[MDic setobject: @ "Apple" Forkey: @ "A"];//add Value-key to
For (ID key in MDic) {
NSLog (@ "%@:%@", Key,[mdic Objectforkey:key]);
}
For-each Loops for fast iterations
28. Hash set
Nsset represents a hash of the collection of storage locations, consistent with HashSet in Java. Each object in the Nsset has a unique hash value, and the duplicate object will only hold one. Therefore, this leads to the object comparison problem in Objective-c, which requires you to implement the following two methods inherited from NSObject:
-(BOOL) IsEqual: (ID) anobject;
-(Nsuinteger) hash;
This is no different from the Java object comparison, two equal objects must have the same hashcode, so both methods must be implemented at the same time.
Similarly, Nsmutableset represents a variable-length hash set.
29. Package class (equivalent to Java wrapper)
The first few container class objects can not hold the basic data structure, enum, struct, nil, how to do? In Java we know that all of the basic data types have corresponding encapsulation classes, such as int---Integer, boolean---boolean, using the wrapper class to wrap the base data type as an object, and the wrapper class itself has methods to return the original base data type. Cocoa uses Nsvalue as the encapsulation class.
Nsrect Rect=nsmakerect (1,2,30,50);//This is a struct that represents a rectangle as mentioned earlier
Nsvalue *v=[nsvalue valuewithbytes: &rect objctype: @encode (nsrect)];
/aluewithbytes requires the address of the incoming wrapper data, which is the first address of the data stored in the variable, we still use the C & as the address operator to calculate the first address of the pointer store.
Objctype requires passing in a string describing the type, size of the data, using the @encode directive to wrap the type to which the data belongs.
Nsmutablearray *marray=[nsmutablearray Arraywithcapacity:3];
[Marray Addobject:v];
Nsrect Rect2;
[[Marray objectatindex:0] GetValue: &rect2];
Nsvalue-(void) GetValue: (void*) The value method can take the contents of the data in the Nsvalue, requiring that the passed in parameter is a pointer, that is, the GetValue method points your incoming pointer to the stored data.
The GetXXX method in general cocoa is the function, which is why the previous getter method does not use get as the prefix of the method.
For the basic data type, you can use a simple nsnumber to encapsulate it, which is a subclass of Nsvalue.
If you want to store null values into the collection class, you can use NSNull, which is created using NSNull *n =[nsnull null];
30. Date Type
The date is represented in Cocoa using the NSDate type.
31, data buffer (actually is a byte array in Java)
Cocoa uses the NSData type to implement buffers for storing binary data types, such as files downloaded from the network.
NSData is an immutable data buffer, and a nsmutabledata is used to store a variable-length data buffer.
32. Write and Read properties (simply a replica of Java serialization and deserialization)
In the iphone's *.ipa file, you can often see the *.plist file, which holds the relevant properties of the program, called the attribute list. In fact, it is Nsarray, Nsdictionary, nsstring, nsdata persistent files.
These types have a member method WriteToFile: (nsstring*) file Atomically:bool is used to write itself to a file. Atomically to yes means that the file is stored in the temporary file area, if the file is saved successfully, and then replaced the original file, the benefit is to prevent errors in saving the file process, but only for small files, because you are equivalent to a temporary file store also put a copy, plus the original file, is two files, if the file is larger, will occupy more users of disk space.
What if the type you want to persist is not the array, dictionary, buffer, and so on? Objective-c also has the same serialization and deserialization support as Java, using the Nscoding protocol. The Nscoding protocol defines the following two methods:
-(void) Encodewithcoder: (nscoder*) coder;
-(ID) Initwithcoder: (nscoder*) decoder;
The first method is equivalent to the encoded object, and the second method decodes back to the object, which is equivalent to defining a new Init method for the type.
33. Replication of objects
The copy of the object is equivalent to the Clone () method in Java, that is, the deep copy of the object, so-called deep replication is to reallocate a storage space and copy the contents of the original object, from these descriptions can be seen, replication will also allocate space, that is, you want to copy out the object release, This is the object created by the Alloc, new, and copy operations as mentioned earlier, and should be manually release.
Whether an object in the Objective-c can be copied depends on whether its type follows the Nscopying protocol, which has a copy method-(ID) Copywithzone: (*nszone) zone needs to be implemented.
34. Multithreading
Objective-c multithreaded Programming and Java language is very similar to the original threading, thread pool Two, the latter is the use of the queue and other mechanisms of the former encapsulation. As in JAVA, the original thread operation uses the thread class, and the thread pool operation uses the class library in java.util.concurrent.*.
The Nsthread type in objective-c represents a thread, nscondition is used to perform a synchronous operation, and is equivalent to the lock object in the java.util.concurrent.* package in Java in functionality and usage.
In addition, OBJECTIVE-C also supports @synchronized instructions for code synchronization, and is similar in Java.
@synchronized (the object to be locked) {
Code that executes synchronously
}
It is also interesting to note that if you want to update a part of the UI, you will need to invoke a method on the main thread of the UI where the new threads are being launched, and the new thread will not have direct access to the main thread's method, which requires the following method in the Run method:
-(void) Performselectoronmainthread: (SEL) Aselector withobject: (ID) arg waituntildone: (BOOL) wait
If you are familiar with the Java swing, you should know that in the UI, most of the update interface must be executed in a single thread, because if the update interface is multithreaded it will be difficult to deal with, Java Swing processing method is to update the interface of the code in a special update UI execution, In fact, iOS is such an idea here.
Objective-c uses nsoperation, nsoperationqueue two types to implement the thread pool operation, Nsopertion is like the runnable in Java, where the main (the name is a bit strange) method is the action you want to do , Nsoperationqueue is a thread pool queue, you only need to add nsoperation to Nsoperationqueue, the queue will retain your nsoperation, and then perform the actions in it until execution is complete. There are multiple actions in the queue, and the queues are executed one after the other in the order that you added, and the tasks in the queue are serial.
Like Java, if the thread pool can meet your business needs, try to use a thread pool instead of the original nsthread, because using a line Cheng the problem that many threads themselves need to handle, and the code is more concise.
35, KVC and KVO (This topic is really advanced)
KVC is the abbreviation for nskeyvaluecoding, which is a nsobject category in the foundation Kit, which you can analogy with the reflection mechanism in Java, which is to dynamically access properties in an object.
KVC when parsing a key string, it will be slower than you call setter, getter, and the compiler can not check your method call in the compiler (because your property name is a string, only the runtime will know if you write wrong), the probability of error will increase, So please do not arbitrarily use KVC, but omit setter, getter method. KVC is typically used for dynamic binding, which is the runtime to determine who calls which method, and the compilation period is not deterministic.
KVO is Nskeyvalueobserving's abbreviation, and it is also a nsobject category,kvo based on the KVC implementation of the foundation kit, based on the Observer design pattern (Observer Pattern) Implementation of a notification mechanism, you can analogy with the JMS in Java, through the way of subscribing to achieve the decoupling of two objects, but can let them call each other. (Please check the information for details)
Comparison of OC and Java