IOS之学习笔记三(简单对象和static和单例)

1、Person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject
{
    NSString *_name;
    int _age;
}
-(void)setName:(NSString *) name andAge:(int) age;
-(void)say:(NSString *)content;
-(NSString *)info;
+(void)foo;
@end

Person.m

#import "Person.h"

@implementation Persion
{
    int test;
}

-(void)say:(NSString *)content
{
    NSLog(@"%@", content);
}

-(NSString *)info
{
    [self test];
    return [NSString stringWithFormat:@"名字:%d, 年龄%d,", _name, _age];
}

+(void)foo
{
    NSLog(@"通过类名调用");
}

-(void)test
{
    NSLog(@"this is a test method");
}
@end

-(void)setName:(NSString *) _name andAge:(int) _age
{
    //记得这里是self->_name不是self._name,一定要注意。
    self->_name = _name;
    self->_age = _age;
}

Person *person = [[Person alloc] init];
[person say:@"hello"];
[person setName:@"chenyu" andAge:26];
NSString *info = [person info];
NSLog(@"info is %@", info);
[Persion foo];

2、id类型可以代表所有对象的类型,可以任何类的对象赋值给id类型变量

id p = [[Person alloc] init];
[p say:@"hello"];

3、oc没有类变量,但是可以通过内部全局变量来模拟类变量
oc也提供了static关键字,但是static不能用于修饰成员变量,只能修饰局部变量,全局变量和函数,static修饰局部变量表示将该局部变量存储在静态存储区,static修饰全局变量用于限制全局变量只能在当前源文件中访问,static修饰函数用于限制函数只能在当前文件中调用

模拟类变量

User.h文件如下

#import <Foundation/Foundation.h>
@interface User : NSObject
+(NSString *)nation;
+(void)setNation:(NSString *)newNation;
@end

User.m文件如下

#import "User.h"
@implement User
static NSString *nation = nil;
+(NSString *)nation
{
    return nation;
}
+(void)setNation:(NSString *)newNation
{
    nation = newNation;
}
@end

int main(int argc, char* argc[])
{
    @autoreleasepool {
[User setNation:@"chenyu"];
        NSLog(@"nation is %@", [User nation]);
    }
}

4、单例模式

Singleton.h文件如下

#import <Foundation/Foundation.h>
@interface Singleton : NSObject
+(id)instance;
@end

Singleton.m文件如下

@implemnet Singleton
static id instance = nil;
+(id)instance
{
   if (instance)
   {
       instance = [[super malloc] init];
   }
   return instance;
}
@end

int main(int argc, char* argc[])
{
    @autoreleasepool {
        NSLog(@"%d", [Singleton instance] == [Singleton instance]);
    }
}
(0)

相关推荐