oc對象讀取屬性值的幾種方法
NSLog(@"Access by message (%@),dot notation (%@),property name (%@),
direct instance variable access (%@)",
[p name],p.name,[p valueForKey:@"name"], p->name);
遍歷類所有屬性名稱
#import <objc/runtime.h>
int i;
int propertyCount = 0;
objc_property_t *propertyList = class_copyPropertyList([aPerson class],
&propertyCount);
for ( i=0; i < propertyCount; i++ ) {
objc_property_t *thisProperty = propertyList + i;
const char* propertyName = property_getName(*thisProperty);
NSLog(@"Person has a property: '%s'", propertyName);
}
遍歷集合的幾種方式
//使用NSEnumerator
NSMutableArray *people =[NSMutableArray arrayWithCapacity:20];
NSEnumerator *enumerator = [people objectEnumerator];
Person *person;
while((person= enumerator.nextObject)!= nil){
NSLog(@"hello,%@",person.name);
}
//使用依次枚舉
for(int i=0;i<[people count];i++){
Person *person = [people objectAtIndex:i];
NSLog(@"hello,%@",person.name);
}
//使用快速枚舉
for(Person *p in people){
NSLog(@"hello,%@",p.name);
}
協(xié)議(Protocol)
類似于java的interface,不同之處在于Oc的類可以在不聲明的情況下實現(xiàn)某個協(xié)議。@optional可以使協(xié)議的某個方法可選實現(xiàn)。
聲明協(xié)議
@protocol Lock
-(void) lock;
-(void) unlock;
@end
聲明類使用協(xié)議
@interface SomeClass:NSObject <Lock>
@end
實現(xiàn)協(xié)議的方法
@implementation SomeClass
-(void)lock{
//do something
}
-(void) unlock{
//do something
}
@end