objective c基本知识

1、减号(加号)

 在c++中我们这样定义一个函数

public void Test(bool flag)

{

  cout<<"hello world!!"<<endl;

}

而在objective c中是:

-(void)Test:(bool)flag

{

  NSLog(@"hello world!!");

}

其中“-”表示一个函数、或者消息的开始,其实就是方法,其实还是比较容易看懂的,(-)(函数返回类型)函数名:(参数类型)参数名,其中如果是多个参数时会稍稍有些不一样,其形式如下:

(-)(函数返回类型)函数名:(参数类型)参数名 secondPara:(参数类型)参数名 threedPara:(参数类型)参数名....

而对于c++而言,则是 public void Test( string str1,string str2,string str3);调用的时候一般都是this.Test("hello"," world","!!!!");

对于objective c而言,调用则会有些繁琐,即[self Test:@"hello" secondPara:@"world" threedPara:@"!!!!"];

其中在实例和函数之间的空格表示调用的关系了,而后面则是参数了其中每个参数之间用空格隔开,这和定义的形式是一样的,其中secondPara、threedPara可以更改,只要在调用的时候一样就可以了。注self就是等价this指针。

2、中括号

在c++中我们调用函数一般是this.Test("hello world!!!");而在objective c中是[self Test:@"hello world!!!"];

3、NS**

对于这种命名方式,其实和历史有关,就是neststep的意思,是当年乔布斯创建的公司。还可以看到其他一些打头的类,比如CF,CA,CG,UI等,CF说的是Core Foundation,CA说的是Core Animation,CG说的是Core Graphics,UI说的是iPhone的User Interface……

4、#import

学过java的就知道,这就是导入的意思,其实就是等价c++中的#include。

5、@interface等

c++中我们定义个类:

public class Test:public Object

{

  string m_str;

  int     m_count;

     void printOut(int count=0)

  {

     if(count = 0)

      m_count = count;

     sprintf(m_str,"this %d coming in",m_count);

     cout<<"m_str"<<endl;

  }

}

objective c的定义如下:

Test.h文件定义

@interface Test:NSObject{

  NSString str1;

  NSString str2;

}

-(void)printOut;

@end 

Test.m文件如下

#import "Test.h"

@implementation Test

-(void)init{

  str1=@"hello world!!!";

  str2=@"l am coming!!";

}

-(void)printOut:{

  NSLog:(str1);

  NSLog:(str2);

}

@end

5、函数调用

  c++中调用Test myTest = new Test(),myTest .printOut("hello world!!!");然后再最后的delete对象。

在objective c中我们是需要这样[[[Test alloc] init:@"hello world"] aurorelease];

6、其他

  1).在objective c中id是一个特殊的变量类型,其实就是可以表示所有类型,当不知道变量类型的时候就可以使用它,

  2).对于NSArray是一个可以存放不同数据类型的数组,各种数据类型,如浮点、字符串、图片等所有。

  3).objective c中的 YES等价于 TRUE,NO 等价于 FALSE。

  4).IBOutlet、IBAction这两个东西其实在语法上没有太大的作用,如果你希望在Interface Builder中能看到这个控件对象,那么在定义的时候前面加上IBOutlet,在IB里就能看到这个对象的outlet,如果你希望在Interface Builder里控制某个对象执行某些动作,就在方法前面加上(IBAction)。

原文地址:https://www.cnblogs.com/xiaoaiyi/p/3873997.html