Programming with OBJECTIVE-C Learning notes

Source: Internet
Author: User

These days the programming with Objective-c again looked aside, found a lot of previously unclear places. Now write down some important points and consolidate the learning effect.

1.objective-c Classes is also Objects (OC class is also an object)

In Objective-c, a class was itself an object with an opaque type called class. Classes can ' t has properties defined using the declaration syntax shown earlier for instances, but they can receive Messa Ges.
The typical use for a class method was as a factory method, which is an alternative to the object allocation and Initializa tion procedure described in Objects is Created dynamically (page 34).
A class is also a special object, and a typical usage is that a method in a class is called a factory method.

2.Use pointers to Keep track of Objects (using pointers to record objects)

Objects normally has a longer life than, the simple scope of a method call. In particular, a object often needs to stay alive longer than the original variable that is created to keep track of it, So an object's memory is allocated and deallocated dynamically.
If you ' re used to using terms like the stack and the HEAP,A local variable was allocated on the stack, while objects was Al Located on the heap.
Here are two sets of terms that explain the differences between local variable and object. The latter is familiar, where local variables are stored in the stack (stack) and objects are stored in the heap.

3.Objects is Created dynamically (object is created dynamically)

The NSObject root class provides a class method, Alloc, which handles this process for you:

?+ (id)alloc;

Notice The return type of this method is ID. This was a special keyword used in objective-c to mean "some kind of object." It's a pointer to an object, like (NSObject *), but is special in the IT doesn ' t use an asterisk.
The Alloc method has one other important task, which are to clear out the memory allocated for the object's properties by s Etting them to zero. This avoids the usual problem of memory containing garbage from whatever were stored before, but isn't enough to Initializ E an object completely.
When you create an object, you call the Alloc method, and the type returned is Id,id is a pointer to the object only, which represents "a class of objects," but it is special that you do not need to add asterisks.
Another function of the Alloc method is to say that the attribute in the object is zeroed, which avoids the effect of the memory garbage.
You need to combine a call to alloc with a call to Init, another NSObject method:

- (id)init;

The Init method is used by a class to make sure its properties has suitable initial values at creation, and are covered in More detail in the next chapter.
The Init method is used to ensure that all parameters are initialized.

4.objective-c is a dynamic Language (OC is an active language)

Because of Objective-c ' s dynamic nature, it doesn ' t matter what the specific class type you use for that pointer-the correct m Ethod is always being called on the relevant object when you send it a message.

id someObject = @"Hello, World!";[someObject removeAllObjects];

OC is a dynamic language, here it is an example, Someobject is a NSString type object, there is no removeallobjects method, but the compiler does not have an error, only throws an exception at runtime. This means that OC only determines the invocation of the method at run time.

5.Most Properties is backed by Instance Variables (most attributes are based on instance variables)

For a property called FirstName, for example, the synthesized instance variable would be called _FirstName.
Should use accessor methods or dot syntax for property access even if you ' re accessing an
Object ' s properties from within it own implementation, in which case you should with self:
The exception to this rule was when writing initialization, deallocation or custom accessor methods, as described later in This section.
For example, if the property name is FirstName, then the synthetic instance variable is named _FirstName
Generally, the property is obtained through the self. syntax.
There are exceptions, and when we initialize, destroy, or customize the Getter/setter method, we need to access the instance variables directly, such as _FirstName.

6.Designated Initializer (Specify initializer)

This part has not been further studied.

7.Properties is Atomic by default (the property is atomic by defaults)

Propertyatomicityisnotsynonymouswithanobject ' Sthreadsafety.
Consider an Xyzperson object in which both a person's first and last names is changed using atomic accessors from one THR ead. If Another thread accesses both names at the same time, the atomic getter methods would return complete strings (without CR ashing), but there's no guarantee that those values would be is the right names relative to each of the other. If the first name is accessed before the "the change", but the last name was accessed after the "change", you'll end up with an Inc Onsistent, mismatched pair of names.
property setting to atomic does not guarantee thread safety, here is an example of a Xyzperson object.

8.Avoid Strong Reference Cycles (avoid circular references)

A common scenario is and the table view have a reference to its delegate and the delegate have a reference back to the TABL E view, as shown in Figure 3-7 (page 59).

Give an example of TableView and delegate to explain why circular references occur.
The the-the-solve-problem is-to-substitute one of the strong references for a weak reference. A Weak reference does not imply ownership or responsibility between the objects, and does not keep an object alive.
To avoid cyclic applications, you can use the weak modifier, such as

@property (weakid delegate;
NSObject * __weak weakVariable;
9. Standard method for sending messages to weak-modified objects
NSObjectself.someWeakProperty//1 if//2//3 //4 nil;
10.Copy Properties maintain their Own Copies (copy-type attribute maintains its own copy)

Examples illustrate why nsstring generally use the copy modifier.

11.Categories and class Extension (categories and classes extensions)

Categories can used to declare either instance methods or class methods but is not usually suitable for declaring Addi tional properties.
The classification can be what class methods and instance methods, but cannot declare properties.
Unlike regular categories, a class extension can add its own properties and instance variables to a class.
Class extensions can increase properties and instance variables.
Property:

@interface XYZPerson ()@propertyNSString *uniqueIdentifier;@end

Instance variable:

@interface XYZPerson () {    id _someCustomInstanceVariable;}
12.Check that Optional Methods is implemented at runtime (runtime checks if the optional method is implemented)

If a method in a protocol are marked as optional, you must check whether an object implements this method before attempting To call it.

NSString *thisSegmentTitle;if ([self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)]){    thisSegmentTitle = [self.dataSource       titleForSegmentAtIndex:index];}

When there is an optional method in the protocol, you need to use the Respondstoselector: method to determine whether an optional method is implemented.

13.Objects Use property to Keep track of Blocks (block as attribute in object)
void (^blockProperty)(void);

You should specify copy as the property attribute, because a block needs to being copied to keep track of it captured state Outside of the original scope. This isn ' t something you need to worry on when using Automatic Reference counting, as it would happen automatically, but It ' s best practice for the property attribute to show the resultant behavior. For more information, see Blocks programming Topics.
Explains why the Block property needs to be decorated with copy.

14.Use __block Variables to Share Storage (shared memory area with __block modifier)

If you need to is able to change the value of a captured variable from within a block, you can use the __block storage Typ e modifier on the original variable declaration.

int42;void (^testBlock)(void) = ^{    NSLog(@"Integer is: %i"84;testBlock();

The value of the default copy variable when the block captures variables that are outside the scope. If you want to change the modified variable, you need to modify it with __block.

15.Avoid Strong Reference Cycles when capturing self (avoid circular references when calling self in block)
- (void)configureBlock {    XYZBlockKeeper * __weakself;    self.block = ^{    [weakSelf doSomething];   // capture the weak reference} }

A circular reference occurs when a message is sent to the self object in a block, and a standard workaround is given.

Programming with OBJECTIVE-C Learning notes

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.