• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

oc学习笔记2 点语法

mysql 搞代码 4年前 (2022-01-09) 17次浏览 已收录 0个评论

先来几段代码,Dog类的.h .m文件 和main.m dog.h #import Foundation/Foundation.h@interface Dog : NSObject{ int _ID; NSString *_name; int _age; float _price;}//凡是用initXXX开头的都是构造函数//init方法实际上没有什么特别的,只是遵循命名约定的普

先来几段代码,Dog类的.h .m文件 和main.m

dog.h

#import @interface Dog : NSObject{    int _ID;    NSString *_name;    int _age;    float _price;}//凡是用initXXX开头的都是构造函数//ini<em style="color:transparent">本文来源gao.dai.ma.com搞@代*码#网</em>t方法实际上没有什么特别的,只是遵循命名约定的普通方法-(id)init;-(id)initWithID:(int)newID;-(id)initWithID:(int)newID andAge:(int)newAge;-(id)initWithID:(int)newID andAge:(int)newAge andPrice:(int)newPrice;@property int ID;@property NSString *name;@property int age;@property float price;@end

dog.m

#import "Dog.h"@implementation Dog-(id)init{    return [self initWithID:1001];}-(id)initWithID:(int)newID{    return [self initWithID:newID andAge:20];}-(id)initWithID:(int)newID andAge:(int)newAge{    return [self initWithID:newID andAge:newAge andPrice:80.0];}-(id)initWithID:(int)newID andAge:(int)newAge andPrice:(int)newPrice{    self=[super init];    if(self){        _ID=newID;        _age=newAge;        _price=newPrice;    }    return self;}@synthesize ID=_ID;@synthesize name=_name;@synthesize age=_age;@synthesize price=_price;@end

main.m

#import #import "Dog.h"#import "NSString+ReverseString.h"#import "Person.h"int main(int argc, const char * argv[]){    @autoreleasepool {        Dog *dog1=[[Dog alloc ] init];        dog1.name=@"syj";        NSLog(@"%@",[dog1 name]);        [dog1 setName:@"ldusyj"];        NSLog(@"%@",dog1.name);    }    return 0;}

先看一下:

@property

@propertyint age;

等同于 –setAge:(int)newAge;

-(void)age;

@synthesize

@synthesize age=_age;

等同于: -(void)setAge:(int)newAge{

age=newAge;

}

-(int)age{

return age;

}

在看一下点:

1.

dog1.name=@"syj";

点放到左边相当于调用其对应的set方法。

等同

[dog1 setName:@"syj"];

2.

NSLog(@"%@",dog1.name);
NSLog(@"%@",[dog1 name]);

这两种情况是相同的效果。相当于get方法。


注意:

-(void)setAge:(int)newAge {     NSLog(@"调用了setAge方法:%i",newAge);     self.age = newAge; }

不能在setAge:方法中使用self.age = newAge,相当于在setAge:方法中调用[self setAge:newAge ], 出现死循环

-(int)age {     NSLog(@"调用了age方法:%i",_age);     return self.age; }

不能在age方法中使用return self.age, 相当于return [self age];, 出现了死循环


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:oc学习笔记2 点语法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址