day1

作者: OneKeyRestore | 来源:发表于2017-11-28 23:29 被阅读0次

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);
}

协议(Protocol)
类似于java的interface,不同之处在于Oc的类可以在不声明的情况下实现某个协议。@optional可以使协议的某个方法可选实现。

声明协议

@protocol Lock
-(void) lock;
-(void) unlock;
@end

声明类使用协议

@interface SomeClass:NSObject <Lock>

@end

实现协议的方法

@implementation SomeClass
-(void)lock{
//do something
}
-(void) unlock{
//do something
}
@end

网友评论

      本文标题:day1

      本文链接:https://www.haomeiwen.com/subject/tazadxtx.html