微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐