Objective-C学习笔记(二)——OC基本语法概述

本文介绍了Objective-C编程语言的基础知识,包括源代码文件扩展名、类的声明、属性声明、方法声明等内容,并通过实例展示了类的声明和实现。
1.源代码文件扩展名对比
                     头文件      实现文件
C语言             .h             .c
C++语言        .h             .cpp
OC语言          .h             .m
OC&C++       .h             .mm


3.类的声明,注意和Java区别,这里类的声明使用interface,而不是Class;以@interface开头,以@end结尾;类名是SimpleClass,继承自NSObject;
@interface SimpleClass:NSObject

@end


4.类的属性声明,属性以@property开头,(readonly)表示是只读的;
@interface Person:NSObject

@property NSString *firstName;
@property NSString *lastName;

@property NSNumber *yearOfBirth;
@property int yearOfBirth;

@property (readonly) NSString *sex;

@end


5.OC中的方法总共分为两种:

减号方法(普通方法又称对象方法)声明,可以理解为Java中的普通的方法,可以用对象进行调用;

加号方法(类方法,又称静态方法)声明,可以理解为Java中用static修饰的方法;


6.减号方法(普通方法又称对象方法)声明:
@interface Person : NSObject

-(void)someMethod;
-(void)someMethodWithValue:(SomeType)value;
-(void)someMethodWithFirstValue:(SomeType)info1 secondValue:(AnotherType)info2;

@end


7.加号方法(类方法,又称静态方法)声明:
@interface NSString : NSObject
+(id)string;
+(id)stringWithString:(NSString *)aString;
+(id)stringWithFormat:(NSString *)foramt,...;
+(id)stringWithContentsOfFile:(NSString *)path encoding:(NSStringEncoding)enc error:(NSError **)error;
+(id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc;
@end


8.类的实现;类的实现用@implementation开头;
#import "XYZPerson.h"
@implementation XYZPerson

@end



9.完整的例子,import表示引入头文件;NSLog表示打印信息;

XYZPerson.h文件
@interface XYZPerson:NSObject
-(void)sayHello;
@end


XYZPerson.m文件
#import "XYZPerson.h"
@implementation XYZPerson
-(void)sayHello{
NSLog(@"Hello,World");

}


本文参考慕课网课程《征战Objective-C》。感谢!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值