您的位置:首页 > 其它

OC入门

2015-09-30 20:28 288 查看

OC与C的区别

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//    程序启动成功了,就会进入这个方法
printf("didFinishLaunchingWithOptions");
printf("didFinishLaunchingWithOptions\n");
//    OC的控制台打印方法, 因为OC是乔布斯前公司 NextStep的, 所有都有NS前缀
//    C语言的字符串 是 "",  OC为了区分,前面加了一个@
//    OC的打印  自带换行符, 带有打印的时间。
NSLog(@"didFinishLaunchingWithOptions");
NSLog(@"a is %d, b is %d, c is %f", 12, 33, 123.0);
//  C语言常用的基础类型, int long
//    OC语言中, 使用NSInteger 代替 int long;
//int a;
//long b;
//NSInteger c;

//    调用C语言函数
function();
//    OC语言的方法调用,需要写在[]中,形式为[A b], A为b的所有者
[self function];
[self functionJiOu:123];
[self qiuHeWithNum:1 anotherNum:100];
NSLog(@"n is %ld",[self chu:1 anotherNum:10 anotherNum:2 anotherNum:5]);
return YES;
}


方法,返回两个数字中,较大的数

- (NSInteger)getMaxNumWithNum:(NSInteger)num anotherNum:(NSInteger)anotherNum{

return num > anotherNum ? num : anotherNum;
}


方法,返回两个数字中,较小的数

- (NSInteger)getMinNumWithNum:(NSInteger)num
anotherNum:(NSInteger)anotherNum{
return num < anotherNum ? num : anotherNum;
}


求数字A 到 数字B 中 能同时被数字C,D整除的数字的数量

- (NSInteger)chu:(NSInteger)num1
anotherNum:(NSInteger)num2
anotherNum:(NSInteger)num3
anotherNum:(NSInteger)num4{
NSInteger n;
NSInteger min = [self getMinNumWithNum:num1 anotherNum:num2];
NSInteger max = [self getMaxNumWithNum:num1 anotherNum:num2];
for (NSInteger i = min; i <= max; i ++) {
if (!(i%num3)&&!(i%num4)) {
n ++;
}

}
return n;
}


判断从A 到 B 之间所有数字的和

-多参数之间 使用(空格+:) :号间隔

-多参数 :前面可以加描述,让他人读代码更容易理解。

- (void)qiuHeWithNum:(NSInteger)number1 anotherNum:(NSInteger)number2{
NSInteger sum;
NSInteger minNum = [self getMinNumWithNum:number2 anotherNum:number1];
NSInteger maxNum = [self getMaxNumWithNum:number1 anotherNum:number2];

for (NSInteger i = minNum; i <= maxNum; i ++) {
sum += i;
}
NSLog(@"sum is %ld", (long)sum);
}


判断一个数字是奇数 还是 偶数

- (void)functionJiOu:(NSInteger)number{
//   如果是奇数,打印出 number 是奇数, 否则打印出 number是偶数
//    使用 %@打印字符串
NSLog(@"%ld 是 %@", (long)number, number%2 == 0 ? @"偶数" : @"奇数" );
}


OC语言的方法

- (void)function{
NSLog(@"我是OC语言方法");
}


C语言的方法

void function(){
printf("我是C语言函数\n");
}


输出结果

didFinishLaunchingWithOptionsdidFinishLaunchingWithOptions
2015-09-30 20:11:06.304 OC入门[3553:293850] didFinishLaunchingWithOptions
2015-09-30 20:11:06.359 OC入门[3553:293850] a is 12, b is 33, c is 123.000000
我是C语言函数
2015-09-30 20:11:06.360 OC入门[3553:293850] 我是OC语言方法
2015-09-30 20:11:06.360 OC入门[3553:293850] 123 是 奇数
2015-09-30 20:11:06.360 OC入门[3553:293850] sum is 5050
2015-09-30 20:11:06.360 OC入门[3553:293850] n is 1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: