NSObject详解

来源:互联网 发布:apache storm java应用 编辑:程序博客网 时间:2024/05/06 16:52

NSObject Class Reference

Initializing a Class

[plain] view plaincopy
  1. 1.+ (void)initialize  
一个类的实例在使用前需要先初始化.

initialize 在一个类中只被调用一次。如果你想为一个类或类的Categories执行独立的初始化,你可以实现load方法。

[plain] view plaincopy
  1. 2.+ (void)load  
无论何时,只要一个类或者Categories只要被添加到Objective-C的运行时就会调用此方法;加载后实现这个方法来执行类的特殊行为。

Creating, Copying, and Deallocating Objects

[plain] view plaincopy
  1. 1.+ (id)alloc  
返回一个新的实例。
必须和init一起使用iClass* iclass = [[iClass alloc] init];
[plain] view plaincopy
  1. 2.+ (id)allocWithZone:(NSZone *)zone  
返回一个新的实例。
必须和init一起使用iClass* iclass = [[iClass allocWithZone:nil] init];

This method exists for historical reasons; memory zones are no longer used by Objective-C.

[plain] view plaincopy
  1. 3.- (id)init  
当一个新对象申请了内存空间,就会立刻调用init方法来初始化这个对象。
在NSObject类中定义的init方法没有初始化,只是返回了self指针。

TheClass *newObject = [[TheClass alloc] init]; alloc和init一起使用

[plain] view plaincopy
  1. 4.- (id)copy  
返回一个通过copyWithZone:创建的实例。

This is a convenience method for classes that adopt the NSCopying protocol. An exception is raised if there is no implementation forcopyWithZone:.

NSObject does not itself support the NSCopying protocol. Subclasses must support the protocol and implement thecopyWithZone: method. A subclass version of thecopyWithZone: method should send the message tosuper first, to incorporate its implementation, unless the subclass descends directly fromNSObject.

[plain] view plaincopy
  1. 5.+ (id)copyWithZone:(NSZone *)zone  
当你需要一个实现NSCopying协议的对象时,可以使用此方法。例如,把一个类对象作为NSDictionary的key值

You should not override this method.

[plain] view plaincopy
  1. 6.- (id)mutableCopy  
当zoon为nil的时候,通过NSMutableCopying 协议方法 mutableCopyWithZone:创建的对象。

对一个采用 NSMutableCopying协议的类来说这是一个方便的方法。如果没有实现mutableCopyWithZone:的话就会抛异常。

This is a convenience method for classes that adopt the NSMutableCopying protocol. An exception is raised if there is no implementation formutableCopyWithZone:.

[plain] view plaincopy
  1. 7.+ (id)mutableCopyWithZone:(NSZone *)zone  
雷同copyWithZone:(NSZone *)zone
[plain] view plaincopy
  1. 8.+ (id)new  

分配一个实例新的内存空间,调用init方法,最后返回一个初始化过的对象。

This method is a combination of alloc andinit. Likealloc, it initializes theisa instance variable of the new object so it points to the class data structure. It then invokes theinit method to complete the initialization process.

Identifying Classes

[plain] view plaincopy
  1. 1.+ (Class)class  
返回一个class”对象“
[plain] view plaincopy
  1. 2.+ (Class)superclass  
返回一个类的父类Class

[plain] view plaincopy
  1. 3.+ (BOOL)isSubclassOfClass:(Class)aClass  
判断一个类是否是另一个类的子类。

Testing Class Functionality

[plain] view plaincopy
  1. 1.+ (BOOL)instancesRespondToSelector:(SEL)aSelector  
判断一个实例变量是否能够调用一个类的方法
比如,
BOOL boolValue = [NSArray instancesRespondToSelector:@selector(initWithArray:)];返回YES;

BOOL boolValue = [NSArrayinstancesRespondToSelector:@selector(arrayWithArray:)];返回NO

Testing Protocol Conformance

[plain] view plaincopy
  1. 1.+ (BOOL)conformsToProtocol:(Protocol *)aProtocol  
判断一个接收者是否能够遵从一个给定的protocol。一个接收者遵从一个协议,可以是直接接受这个协议,也可以继承一个已经接受这个协议的类。

Obtaining Information About Methods

[plain] view plaincopy
  1. 1.- (IMP)methodForSelector:(SEL)aSelector  

定位并且返回接收者实现该方法的地址,因此可以作为一个方法来调用。

传入参数aSelector必须是有效切非空的,可以用respondsToSelector: 这个方法提前判断。

[plain] view plaincopy
  1. @interface TestIMP : NSObject  
  2.   
  3. - (void)saySomething;  
  4.   
  5. @end  
  6.   
  7. @implementation TestIMP  
  8.   
  9. - (void)saySomething  
  10. {  
  11.     NSLog(@"invoke saySomething");  
  12. }  
  13.   
  14. @end  
  15.   
  16. // For Test  
  17. TestIMP *testIMP = [[TestIMP alloc] init];  
  18.   
  19. SEL aSelector = @selector(saySomething);  
  20.   
  21. IMP imp = [testIMP methodForSelector:aSelector];  
  22.   
  23. imp(testIMP, aSelector);  
[plain] view plaincopy
  1. 2.+ (IMP)instanceMethodForSelector:(SEL)aSelector  
- (IMP)methodForSelector:(SEL)aSelector
[plain] view plaincopy
  1. 3.+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector  
返回NSMethodSignature对象,这个对象包含被标示的实例方法的描述。
[plain] view plaincopy
  1. 4.- (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector  
+ (NSMethodSignature *)instanceMethodSignatureForSelector:(SEL)aSelector

Describing Objects

[plain] view plaincopy
  1. 1.+ (NSString *)description  
以字符串的形式返回对接收者类内容的描述。

Discardable Content Proxy Support

[plain] view plaincopy
  1. 1.- (id)autoContentAccessingProxy  
创建一个接收者对象的代理。

Sending Messages

[plain] view plaincopy
  1. 1.- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay  
延时调用在当前线程使用默认模式的方法
[plain] view plaincopy
  1. 2.- (void)performSelector:(SEL)aSelector withObject:(id)anArgument afterDelay:(NSTimeInterval)delay inModes:(NSArray *)modes  
延时调用在当前线程使用特定模式的方法

anArgument

如果想把需要的数据传给Selector方法中,需要设置anArgument参数,对应Selector就应是带参数的方法

modes
如果这个参数为空或者数组中没有数据,那么就不会调用Selector方法。
[plain] view plaincopy
  1. [self performSelector:@selector(doSomething:)  
  2.                withObject:[NSArray arrayWithObjects:@"AObject", @"BObject", nil]  
  3.                afterDelay:1.0  
  4.                   inModes:[NSArray arrayWithObjects:NSDefaultRunLoopMode, nil]];  
  5.   
  6. - (void)doSomething:(id)sender  
  7. {  
  8.     NSLog(@"invoke doSomething");  
  9.   
  10.     NSLog(@"%@", sender);  
  11. }  
[plain] view plaincopy
  1. 3.- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait  
以默认的方式在主线程中调用一个方法
wait
如果设置为YES那么将阻塞当前线程,设置为NO将立刻调用Selector方法
如果当前线程也是主线程,那么设置为YES,Selector方法将会立即调用,arg信息也会立即传输。
这个方法是不可以被取消的,如果想调用取消方法可以使用performSelector:withObject:afterDelay:或者performSelector:withObject:afterDelay:inModes:方法
[plain] view plaincopy
  1. 4.- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array  
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait,只是多了一个可以选择RunLoop模式的参数。
[plain] view plaincopy
  1. 5.- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait  
在指定的线程中执行指定的Selector方法。
其它内容与第3条相同。
[plain] view plaincopy
  1. 6.- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thread withObject:(id)arg waitUntilDone:(BOOL)wait modes:(NSArray *)array  
是多了一个可以选择RunLoop模式的参数,其它与第5条相同。
[plain] view plaincopy
  1. 7.- (void)performSelectorInBackground:(SEL)aSelector withObject:(id)arg  
在一个新的后台线程中调用Selector方法
[plain] view plaincopy
  1. 8.+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget  
取消执行先前用performSelector:withObject:afterDelay:这个方法创建的实例方法。取消的只是当前RunLoop里执行的方法而不是所有RunLoop.

performSelector:onThread:withObject:waitUntilDone:performSelectorInBackground:withObject:执行的方法不能被取消。

[plain] view plaincopy
  1. 9.+ (void)cancelPreviousPerformRequestsWithTarget:(id)aTarget selector:(SEL)aSelector object:(id)anArgument  
同第8个方法,只是多了Selector方法和要传递的数据。但是经测试发现这个方法不能取消performSelector:withObject:afterDelay:执行的方法。(有知道原因的朋友就留言,谢谢)
测试方法如下:
[plain] view plaincopy
  1. [self performSelector:@selector(doSomething:)  
  2.                withObject:@"performSelector"  
  3.                afterDelay:1.0];  
  4. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(threadAction) object:nil];  

Forwarding Messages

[plain] view plaincopy
  1. 1.- (id)forwardingTargetForSelector:(SEL)aSelector  
返回消息被第一个转发的对象。
[plain] view plaincopy
  1. 2.- (void)forwardInvocation:(NSInvocation *)anInvocation  
实例如下:
[plain] view plaincopy
  1. @interface Car : NSObject  
  2. {  
  3.     NSString *_name;  
  4.       
  5.     NSArray  *_array;;  
  6. }  
  7.   
  8. @end  
  9.   
  10. #import "Car.h"  
  11.   
  12. @implementation Car  
  13.   
  14. - (id)init  
  15. {  
  16.     self = [super init];  
  17.     if (self) {  
  18.         _name = [[NSString alloc] initWithString:@"I AM A CAR~~"];  
  19.         _array = [[NSArray alloc] initWithObjects:@"1", @"2", nil];  
  20.     }  
  21.     return self;  
  22. }  
  23.   
  24. - (NSMethodSignature *)methodSignatureForSelector:(SEL)aSelector  
  25. {  
  26.     NSMethodSignature* signature = [super methodSignatureForSelector:aSelector];  
  27.     if (signature == nil)  
  28.     {  
  29.         signature = [_array methodSignatureForSelector:aSelector];  
  30.     }  
  31.     NSUInteger argCount = [signature numberOfArguments];  
  32.     for (NSInteger i=0 ; i<argCount ; i++)  
  33.     {  
  34.         NSLog(@"%s" , [signature getArgumentTypeAtIndex:i]);  
  35.     }  
  36.     NSLog(@"methodReturnType:%s, methodReturnLength:%d" , [signature methodReturnType] , [signature methodReturnLength]);  
  37.     NSLog(@"signature:%@" , signature);  
  38.     return signature;  
  39. }  
  40.   
  41. - (void)forwardInvocation:(NSInvocation *)anInvocation  
  42. {  
  43.     SEL seletor = [anInvocation selector];  
  44.     if ([_array respondsToSelector:seletor])  
  45.     {  
  46.         [anInvocation invokeWithTarget:_array];  
  47.     }  
  48.     else  
  49.     {  
  50.         [super forwardInvocation:anInvocation];  
  51.     }  
  52.       
  53. }  
  54.   
  55. - (id)forwardingTargetForSelector:(SEL)aSelector  
  56. {  
  57.     NSLog(@"forwardingTargetForSelector");  
  58.       
  59.     if ([_array respondsToSelector:aSelector])  
  60.     {  
  61.         return _array;  
  62.     }  
  63.     return nil;  
  64. }  
  65.   
  66. - (void)dealloc  
  67. {  
  68.     [_name  release];  
  69.     [_array release];  
  70.       
  71. <span style="white-space:pre">  </span>[super dealloc];  
  72. }  
  73.   
  74. @end  

测试方法如下:

[plain] view plaincopy
  1. Car *car = [[Car alloc] init];  
  2. NSLog(@"length = %d", [car count]);  
  3. [car release];  
car实例本来没有count方法,但是通过消息转发实现了count方法。
部分参考http://blog.csdn.net/freshforiphone/article/details/7381329

Dynamically Resolving Methods

[plain] view plaincopy
  1. 1.+ (BOOL)resolveClassMethod:(SEL)name  
动态的为一个类方法提供了一个SEL实现方法。返回YES表明这个方法已经找到并被添加到接收者,否则返回NO。
[plain] view plaincopy
  1. 2.+ (BOOL)resolveInstanceMethod:(SEL)name  
动态的为一个实例方法提供了一个SEL实现方法。返回YES表明这个方法已经找到并被添加到接收者,否则返回NO。
实例如下:

[plain] view plaincopy
  1. @interface Person : NSObject  
  2. {  
  3.     NSString *name;  
  4.     float weight;  
  5. }  
  6.   
  7. @property (retain,readwrite) NSString* name;  
  8. @property (readonly)float weight;  
  9. @property float height;  
  10.   
  11. -(Person*) initWithWeight: (int) weight;  
  12. -(void) print: (NSString*) str;  
  13. @end  
  14.   
  15. void dynamicMethod(id self,SEL _cmd,float w)  
  16. {  
  17.     printf("dynamicMethod-%s\n",[NSStringFromSelector(_cmd) cStringUsingEncoding:NSUTF8StringEncoding]);  
  18.     printf("%f\n",w);  
  19. }  
  20.   
  21. @implementation Person  
  22. @synthesize name;  
  23. @synthesize weight;  
  24.   
  25. @dynamic height; // 注意这里  
  26. // 在实现类中使用了@dynamic指令  
  27.   
  28.   
  29.   
  30. -(Person*) initWithWeight: (int) w  
  31. {  
  32.     self=[super init];  
  33.     if (self)  
  34.     {  
  35.         weight=w;  
  36.     }  
  37.       
  38.     return self;  
  39. }  
  40.   
  41. -(void) print: (NSString*) str  
  42. {  
  43.     NSLog(@"%@%@",str,name);  
  44. }  
  45.   
  46. + (BOOL) resolveInstanceMethod: (SEL) sel  
  47. {  
  48.     NSString *methodName=NSStringFromSelector(sel);  
  49.     BOOL result=NO;  
  50.       
  51.     //看看是不是我们要动态实现的方法名称  
  52.     if ([methodName isEqualToString:@"setHeight:"])  
  53.     {  
  54.         class_addMethod([self class], sel, (IMP) dynamicMethod,"v@:f");  
  55.         result=YES;  
  56.     }  
  57.       
  58.     return result;  
  59. }  
  60.   
  61. + (BOOL)resolveClassMethod:(SEL)sel  
  62. {  
  63.     NSString *methodName=NSStringFromSelector(sel);  
  64.     BOOL result=NO;  
  65.       
  66.     //看看是不是我们要动态实现的方法名称  
  67.     if ([methodName isEqualToString:@"setHeight:"])  
  68.     {  
  69.         class_addMethod([self class], sel, (IMP) dynamicMethod,"v@:f");  
  70.         result=YES;  
  71.     }  
  72.       
  73.     return result;  
  74. }  
  75.   
  76. -(void) dealloc  
  77. {  
  78.     [self setName:nil];  
  79.     [super dealloc];  
  80. }  
  81.   
  82. @end  

测试方法如下:

[plain] view plaincopy
  1. Person *person = [[Person alloc] init];  
  2. [person setHeight:100.0];  
具体参考http://blog.csdn.net/namehzf/article/details/6904500    http://blog.csdn.net/ios_developer/article/details/9283199

Error Handling

[plain] view plaincopy
  1. 1.- (void)doesNotRecognizeSelector:(SEL)aSelector  
处理不被接收者识别的信息。

Archiving

[plain] view plaincopy
  1. 1.- (id)awakeAfterUsingCoder:(NSCoder *)aDecoder  


[plain] view plaincopy
  1. 2.- (Class)classForCoder  


[plain] view plaincopy
  1. 3.- (Class)classForKeyedArchiver  


[plain] view plaincopy
  1. 4.+ (NSArray *)classFallbacksForKeyedArchiver  


[plain] view plaincopy
  1. 5.+ (Class)classForKeyedUnarchiver  

[plain] view plaincopy
  1. 6.- (id)replacementObjectForCoder:(NSCoder *)aCoder  

[plain] view plaincopy
  1. 7.- (id)replacementObjectForCoder:(NSCoder *)aCoder  

[plain] view plaincopy
  1. 8.+ (void)setVersion:(NSInteger)aVersion  

[plain] view plaincopy
  1. 9.+ (NSInteger)version  
获得指定给某一个类的版本号码。
如果没有设置版本号码,默认是0。

Don’t simply send version to the return value of class—a subclass version number may be returned instead.

Deprecated Methods

[plain] view plaincopy
  1. 1.- (void)finalize  

NSObject Protocol

Identifying Classes

[plain] view plaincopy
  1. 1.- (Class)class  
返回实例变量的Class对象,与 + (Class)class 相同。
[plain] view plaincopy
  1. 2.- (Class)superclass  
返回父Class,与 +(Class)superclass相同。

Identifying and Comparing Objects

[plain] view plaincopy
  1. 1.- (BOOL)isEqual:(id)anObject  
判断两个对象是否相等。
[plain] view plaincopy
  1. 2.- (NSUInteger)hash  
返回一个整数,可以在哈希表结构中当作一个地址。如果两个变量isEqual:相等,那么他们的hash值一定相同。
[plain] view plaincopy
  1. 3.- (id)self  
返回自己。

Testing Object Inheritance, Behavior, and Conformance

[plain] view plaincopy
  1. 1.- (BOOL)isKindOfClass:(Class)aClass  
判断一个变量是否是一个给定类的变量或者任何一个继承该类的类变量。
[plain] view plaincopy
  1. 可以这样来使用:  
  2. ShakeViewController *shake = [[ShakeViewController alloc] init];  
  3.       
  4. BOOL boolValue = [shake isKindOfClass:[NSObject class]];  

[plain] view plaincopy
  1. // DO NOT DO THIS!  
  2. if ([myArray isKindOfClass:[NSMutableArray class]])  
  3. {  
  4.     // Modify the object  
  5. }  
[plain] view plaincopy
  1. 2.- (BOOL)isMemberOfClass:(Class)aClass  
判断某一个实例是否是这个类的实例变量。
[plain] view plaincopy
  1. BOOL boolValue = [shake isMemberOfClass:[NSObject class]];  
  2. boolValue=NO,不支持继承类的判断  
[plain] view plaincopy
  1. 3.- (BOOL)respondsToSelector:(SEL)aSelector  
[plain] view plaincopy
  1. ShakeViewController *shake = [[ShakeViewController alloc] init];  
  2. BOOL boolValue = [shake respondsToSelector:@selector(parentViewController)];  
  3. 返回YES。  
  4. BOOL boolValue = [[shake superclass] respondsToSelector:@selector(parentViewController)];  
  5. 返回NO。  
  6. BOOL boolValue = [ShakeViewController instancesRespondToSelector:@selector(parentViewController)];  
  7. 返回YES。  
  8. BOOL boolValue = [[shake superclass] instancesRespondToSelector:@selector(parentViewController)];  
  9. 返回YES。  
[plain] view plaincopy
  1. 4.- (BOOL)conformsToProtocol:(Protocol *)aProtocol  
同+ (BOOL)conformsToProtocol:(Protocol *)aProtocol

Describing Objects

[plain] view plaincopy
  1. 1.- (NSString *)description  
同 + (NSString *)description
[plain] view plaincopy
  1. 2.- (NSString *)debugDescription  
同+ (NSString *)debugDescription

Sending Messages

[plain] view plaincopy
  1. 1.- (id)performSelector:(SEL)aSelector  
[plain] view plaincopy
  1. 2.- (id)performSelector:(SEL)aSelector withObject:(id)anObject  
[plain] view plaincopy
  1. 3.- (id)performSelector:(SEL)aSelector withObject:(id)anObject withObject:(id)anotherObject  
带两个参数的。

Identifying Proxies

[plain] view plaincopy
  1. 1.- (BOOL)isProxy  
判断一个实例不继承自NSObject,如果返回NO就是继承自NSObject,反之返回YES

Obsolete Methods

[plain] view plaincopy
  1. 1.- (id)retain  
增加接收者的引用计数。
[plain] view plaincopy
  1. 2.- (oneway void)release  
减少接收者的引用计数。
[plain] view plaincopy
  1. 3.- (id)autorelease  

Decrements the receiver’s retain count at the end of the current autorelease pool block. (required)

[plain] view plaincopy
  1. 4.- (NSUInteger)retainCount  
[plain] view plaincopy
  1. 5.- (NSZone *)zone  

Zones are deprecated and ignored by most classes that have it as a parameter. (required)

0 0
原创粉丝点击