day1

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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容