IOS---OC section

Source: Internet
Author: User

1. Naming conventions

Object type and name match to avoid confusion

-(void) SetUrl: (NSString *) url;//wrong naming method//changed to-(void) seturlstring: (NSString *) string;-(void) SetUrl: (Nsurl *) URL;

Static variables (including scopes) begin with S, and the complete variables start with g, and in general, you should avoid using global variables other than constants:

Static Mything *ssharedinstance

Constants start with K in Cocoa and core foundation, not in cocoa, and it is recommended that the (static) constants in the file scope begin with K:

static const Nsuinteger kmaximumnumberofrows=3; NSString *const [email protected] "somethinghappeded";

Method parameter name usually add one article (a,an,the) (Landlord Note: Seemingly not very common AH), in this way to name the parameters can be avoided with the method of local variables and instance name confusion

The instance variable begins with an underscore

The class name begins with an uppercase letter, the method name and variable name should start with a lowercase letter, all class names, and the method names are separated by camel case (that is, the first letter of each word), instead of underlining

2. Automatic reference counting

ARC is not garbage collection, it's just a compiler optimization, so it can't handle circular reference issues:

Garbage collection mechanism if the reference link of an external object to object A is interrupted, both object A and object B are destroyed, but the reference count of arc is greater than 1 because of A/b reference, so the management of strong references must be done in iOS development

There are two main types of relationships for attributes: strong and weak, equivalent to retain and assign in non-ARC environments, as long as there is a strong reference object that will persist and will not be destroyed. The weak reference is automatically set to nil when the referenced object is destroyed, so the delegate property should always be declared as weak. Weak.

3. Properties

In the header file declaration of the public property, the. m file declares the private attribute:

Myclass.h@interface Class:nsobject@property (nonatomic,readwrite,weak) ID delegate; @property (Noatomic,readonly, Strong) NSString *readonlystring;
@end//myclass.m@interface MyClass () @property (Noatomic,readwrite,strong) nsstring *readonlystring; @property ( Noatomic,strong) NSString *privatestring;
@end

The compiler automatically creates several variables _delegate,_readonlystring,_privatestring, but these instance variables can only be called in Init,dealloc

You can also see that the readonlystring variable was re-declared in the. m file, adding a setter to the private method for it

Modifier keywords for the property:

1) atomicity (atomic,nonatomic)

The intent is that the accessor method of the property is thread-safe and does not guarantee that the entire object is thread-safe. For example, using Nsmutablearray to declare a stuff, use

Self.stuff and Self.stuff=otherstuff (access only), while accessing the array using the Objectatindex method is not thread-safe.

However, if the attribute does not require other threads to access it, the use of atomic attributes is a great waste, so the usual case is nonatomic

2) Read-write properties (ReadWrite and ReadOnly)

3) Set method modifier keywords (weak,strong,copy)

Note that the copy decoration is used for immutable classes such as NSString and Nsarray

property is used to represent the state of an object, the Getter method must have no external side effects, execute faster, and should not be blocked.

Properties and private instance variables, you can use private instance variables in @implementation

such as @implementation{

NSString *_name;

}

The default storage type is strong

4. Memory

Some of the scopes used, or accessors must be used instead of instance variables:

KVO (key value observation key-value observing)

Properties can be automatically observed, which can be called Willchangevalueforkey: and Didchangevalueforkey: Method when modifying a property.

Side effects (the landlord is not very understanding of side effects)

A class or subclass may reference side effects in the method you set. There may be some notifications or events registered to Nsundomanager, which should not be ignored unless it is really necessary. Similarly, a class or subclass might use the cache in the Fetch method, while accessing the instance variable directly does not use the cache.

Lock

Using instance variables directly in multithreaded code can break the lock mechanism, not to mention the consequences.

Where the memory should not be used:

Internal memory

Dealloc method

Initialization method: Here you can use _value instead of attributes

5. Classification and extension

Category of individuals think it is more useful. You can reduce inheritance by adding new methods to existing classes, similar to the extension methods in C #

Classifications are used to break down a large class into several easily maintainable classes in a modular way.

The classification declaration is very simple, similar to the interface, in parentheses after the class name to write the classification name can be:

@interface Nsmutablestring (Capitalize)

-(void) capitalize

@end

Capitalize is the name of the category. Technically, methods can be overridden in a classification, but it is not recommended to do so, and if two categories contain a method of the same name, it is not possible to predict which method will be used.

With regard to classification, it is reasonable to add some applicable methods to the existing classes. Use the name of the original class name + classification as the name of the new header file and implementation file.

For example, add a simple classification of myextensions for NSDate:

Nsdate+myextensions.h@interface NSDate (myextensions)-(Nstimeinterval) timeintervaluntilnow; @end;//NSDate+ Myextensions.m@implementation NSDate (myextensions)-(nstimeinterval) timeintervaluntilnow{    return [self Timeintervalsincenow];} @end

If you just add a few of the few methods that you use, it's a good way to put those methods in the MyExtensions class, but it's a tradeoff to prevent code bloat.

Associating references adding data to a category

You cannot create an instance variable in a taxonomy, but you can create an association reference to add key-value data for any object by associating a reference.

Because attributes cannot be synthesized in the classification,

Like a statement.

The person class, and adds a taxonomy for it email@interface person:nsobject@property (nonatomic,copy) nsstring *name; @end; @implementation person@end;//Add a category #import <objc/runtime.h> @interface person (emailadress) @property (nonatomic,copy) nsstring *emailadress, @end;////If this is the case, there is an error that the attribute cannot be retrieved or copied at the time of reference or copy//Because the attribute cannot be synthesized in the classification//@implementation person (emailadress)//@end; /correct procedure @implementation person (emailadress) static char emailadresskey;-(NSString *) Emailadress{return objc_ Getassociateobject (Self,&emailadresskey);} -(void) Setemailadress: (NSString *) Emailadress{objc_setassociateobject (SELF,&EMAILADRESSKEY,EMAILADRESS,OBJC _associate_copy);} @end;

You can see that the associated reference is a key-based memory address, not a value for the keys.

If you attach a related object to a warning panel or a warning control, using an associated reference is a very good form.

Objc_setassociatedobject (< #id Object#>, < #const void *key#>, < #id Value#>, < #objc_ Associationpolicy policy#>)//(Target class instance, association reference key, associated reference value
, copy, assign, preserve semantics)
Objc_getassociatedobject (< #id object#>,< #const void *key#>)//(Target class instance, association reference key)
#import "ViewController.h" #import <objc/runtime.h> @implementation viewcontrollerstatic const Char krepresentedobject;-(ibaction) dosomething: (ID) Sender {  Uialertview *alert = [[Uialertview alloc]                        initwithtitle:@ "Alert" Message:nil                        delegate:self                        cancelbuttontitle:@ "OK"                        Otherbuttontitles:nil];  Objc_setassociatedobject (Alert, &krepresentedobject,                            sender,                           objc_association_retain_nonatomic);  [Alert show];  } -(void) Alertview: (Uialertview *) Alertview Clickedbuttonatindex: (Nsinteger) buttonindex {  UIButton *sender = OBJC _getassociatedobject (Alertview,                                               &krepresentedobject);  Self.buttonLabel.text = [[Sender Titlelabel] text];} @end

Class extension

Look, the internet says it can be a category. An anonymous class that can freely declare composition attributes, but the declared method must be implemented in implementation

6. Agreement

Declaring an agreement

@protocol name <NSObject>

@required

Must be implemented by

@optional

Select the implemented

The protocol and the class can inherit, the protocol always inherits <nsobject>,nsobject is divided into a class and a protocol

Entrustment Agreement (Delegate Protocol)

The first argument is a delegate object, such that a delegate can manage multiple delegate objects

An attribute is also required after the protocol is created to facilitate its operation

@property (Nonatomic,weak) id<mydelegate>delegate;

IOS---OC section

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.