Objective-C语法总结_第1页
Objective-C语法总结_第2页
Objective-C语法总结_第3页
Objective-C语法总结_第4页
Objective-C语法总结_第5页
已阅读5页,还剩27页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

一、XCode、Objective-C、Cocoa说的是几样东西?答案:三样东西。XCode:你可以把它看成是一个开发环境,就好像Visual Studio或者Netbeans或者SharpDevelop一样的玩意。你可以将Interface Builder认为是Visual Studio中用来画界面的那部分功能单独提出来的程序。Objective-C:这是一种语言,就好像c+是一种语言,Java是一种语言,c#是一种语言,莺歌历史也是一种语言一样。Cocoa:是一大堆函数库,就好像MFC、.NET、Swing这类玩意,人家已经写好了一堆现成的东西,你只要知道怎么用就可以了。有些人会比较容易混淆Objective-C和Cocoa,就好像有些人会混淆c#和.NET一样。这两个东西真的是两个不一样的东西。二、Objective-C是什么?你可以把它认为是语法稍稍有点不一样的c语言。虽然第一眼望上去你可能会认为它是火星语,和你所认知的任何一种语言都不一样。先简单列出一点差别:问题一:我在程序中看到大量的减号、中括号和NS*这种东西,他们是什么玩意儿?1 减号(或者加号)减号表示一个函数、或者方法、或者消息的开始,怎么说都行。比如c#中,一个方法的写法可能是:private void hello(bool ishello)/OOXX用Objective-C写出来就是-(void) hello:(BOOL)ishello/OOXX挺好懂的吧?不过在Objective-C里面没有public和private的概念,你可以认为全是public。而用加号的意思就是其他函数可以直接调用这个类中的这个函数,而不用创建这个类的实例。2 中括号中括号可以认为是如何调用你刚才写的这个方法,通常在Objective-C里说“消息”。比如C#里你可以这么写:this.hello(true);在Objective-C里,就要写成:self hello:YES;3 NS*老乔当年被人挤兑出苹果,自立门户的时候做了个公司叫做NextStep,里面这一整套开发包很是让一些科学家们喜欢,而现在Mac OS用的就是NextStep这一套函数库。这些开发NextStep的人们比较自恋地把函数库里面所有的类都用NextStep的缩写打头命名,也就是NS*了。比较常见的比如:NSLogNSStringNSIntegerNSURLNSImage你会经常看到一些教学里面会用到:NSLog (%d,myInt);这句话主要是在console里面跟踪使用,你会在console里面看到myInt的值(在XCode里面运行的时候打开dbg窗口即可看到)。而我们在其他开发环境里面可能会比较习惯使用MessageBox这种方式进行调试。你还可以看到其他名字打头的一些类,比如CF、CA、CG、UI等等,比如CFStringTokenizer 这是个分词的东东CALayer 这表示Core Animation的层CGPoint 这表示一个点UIImage 这表示iPhone里面的图片CF说的是Core Foundation,CA说的是Core Animation,CG说的是Core Graphics,UI说的是iPhone的User Interface还有很多别的,等你自己去发掘了。问题二、#import、interface这类玩意说的是什么?1、#import 你可以把它认为是#include,一样的。但是最好用#import,记住这个就行了。2、interface等等比如你在c#中写一个抓孩子类的定义:public class Kids : Systemprivate string kidName=”mykid”;private string kidAge=“15”;private bool isCaughtKid()return true;当然,上面的写法不一定对,就是个用于看语法的举例。在Objective-C里就得这么写:先写一个kids.h文件定义这个类:interface Kids: NSObject NSString *kidName;NSString *kidAge;-(BOOL) isCaughtKid:;end再写一个kids.m文件实现:#import “kids.h”implementation Kids-(void) init kidName=”mykid”;kidAge=”15”;-(BOOL) isCaughtKid:return YES;end这个写法也不一定对,主要是看看语法就行了。-_-b问题三、一个方法如何传递多个参数?一个方法可以包含多个参数,不过后面的参数都要写名字。多个参数的写法(方法的数据类型) 函数名: (参数1数据类型) 参数1的数值的名字 参数2的名字: (参数2数据类型) 参数2值的名字 . ;举个例子,一个方法的定义:-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName;实现这个函数的时候:-(void) setKids: (NSString *)myOldestKidName secondKid: (NSString *) mySecondOldestKidName thirdKid: (NSString *) myThirdOldestKidName大儿子 = myOldestKidName;二儿子 = mySecondOldestKidName;三儿子 = myThirdOldestKidName;调用的时候:Kids *myKids = Kids alloc init;myKids setKids: ”张大力” secondKid: ”张二力” thirdKid: ”张小力”;而如果你用c#写这个方法,大致的写法可能是public void setKids( string myOldestKidName,string mySecondOldestKidName,string myThirdOldestKidName)调用的时候大概的写法可能是:Kids myKids = new Kids();myKids.setKids (“张大力”, “张二力”, “张小力”);明白了吧?其实不怎么难看懂。基本上,如果你能了解下面这段代码的转换关系,你Objective-C的语法也就懂了八成了:MyClass allocinit:foo bar autorelease;转换成C#或者Java的语法也就是:MyClass.alloc().init(foo.bar().autorelease();三、其他的一些东西其实这些本站之前的文章有所提及,这里再详细解释一下。1、 id:Objective-C有一种比较特殊的数据类型是id。你可以把它理解为“随便”。在Objective-C里,一切东西都是指针形式保存,你获取到的就是这个对象在内存的位置。那么id就是你知道这个位置,但是不知道里面是啥的时候的写法。2、 同一个数组可以保存不同的对象:比如一个数组NSArray,这种数组里面可以保存各种不同的对象,比如这个数组里:myArray Console 就可以看到NSLog的记录. NSLog(log: % , myString);NSLog(log: %f , myFloat);NSLog(log: %i , myInt);图片显示不需要UI资源绑定,在屏幕任意处显示图片。 下面的代码可以被用到任意 View 里面。 CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);UIImageView *myImage = UIImageView alloc initWithFrame:myImageRect;myImage setImage:UIImage imageNamed:myImage.png;myImage.opaque = YES; / explicitly opaque for performanceself.view addSubview:myImage;myImage release;应用程序边框大小我们应该使用bounds来获得应用程序边框。不是用applicationFrame。applicationFrame还包含了一个20像素的status bar。除非我们需要那额外的20像素的status bar。 Web viewUIWebView类的调用. CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);UIWebView *webView = UIWebView alloc initWithFrame:webFrame;webView setBackgroundColor:UIColor whiteColor;NSString *urlAddress = ;NSURL *url = NSURL URLWithString:urlAddress;NSURLRequest *requestObj = NSURLRequest requestWithURL:url;webView loadRequest:requestObj;self addSubview:webView; webView release;显示网络激活状态图标在iPhone的状态栏的左上方显示的一个icon假如在旋转的话,那就说明现在网络正在被使用。 UIApplication* app = UIApplication sharedApplication;workActivityIndicatorVisible = YES; / to stop it, set this to NOAnimation: 一组图片连续的显示一组图片 NSArray *myImages = NSArray arrayWithObjects:UIImage imageNamed:myImage1.png,UIImage imageNamed:myImage2.png,UIImage imageNamed:myImage3.png,UIImage imageNamed:myImage4.gif,nil;UIImageView *myAnimatedView = UIImageView alloc;myAnimatedView initWithFrame:self bounds;myAnimatedView.animationImages = myImages;myAnimatedView.animationDuration = 0.25; / secondsmyAnimatedView.animationRepeatCount = 0; / 0 = loops forevermyAnimatedView startAnimating;self addSubview:myAnimatedView;myAnimatedView release;Animation: 移动一个对象让一个对象在屏幕上显示成一个移动轨迹。注意:这个Animation叫fire and forget。也就是说编程人员不能够在animation过程中获得任何信息(比如当前的位置)。假如你需要这个信息的话,那么就需要通过animate和定时器在必要的时候去调整x&y坐标。 CABasicAnimation *theAnimation;theAnimation=CABasicAnimation animationWithKeyPath:transform.translation.x;theAnimation.duration=1;theAnimation.repeatCount=2;theAnimation.autoreverses=YES;theAnimation.fromValue=NSNumber numberWithFloat:0;theAnimation.toValue=NSNumber numberWithFloat:-60;view.layer addAnimation:theAnimation forKey:animateLayer;NSString和int类型转换下面的这个例子让一个text label显示的一个整型的值。 currentScoreLabel.text = NSString stringWithFormat:%d, currentScore;正泽表达式 (RegEx)当前的framework还不支持RegEx。开发人员还不能在iPhone上使用包括NSPredicate在类的regex。但是在模拟器上是可以使用NSPredicate的,就是不能在真机上支持。可以拖动的对象items下面展示如何简单的创建一个可以拖动的image对象:1. 创建一个新的类来继承UIImageView。 interface myDraggableImage : UIImageView 2. 在新的类实现的时候添加两个方法: - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event / Retrieve the touch pointCGPoint pt = touches anyObject locationInView:self;startLocation = pt;self superview bringSubviewToFront:self;- (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event / Move relative to the original touch pointCGPoint pt = touches anyObject locationInView:self;CGRect frame = self frame;frame.origin.x += pt.x - startLocation.x;frame.origin.y += pt.y - startLocation.y;self setFrame:frame;3. 现在再创建一个新的image加到我们刚创建的UIImageView里面,就可以展示了。 dragger = myDraggableImage alloc initWithFrame:myDragRect;dragger setImage:UIImage imageNamed:myImage.png;dragger setUserInteractionEnabled:YES;震动和声音播放下面介绍的就是如何让手机震动(注意:在simulator里面不支持震动,但是他可以在真机上支持。) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);Sound will work in the Simulator, however some sound (such as looped) has been reported as not working in Simulator or even altogether depending on the audio format. Note there are specific filetypes that must be used (.wav in this example). SystemSoundID pmph;id sndpath = NSBundle mainBundle pathForResource:mySound ofType:wav inDirectory:/;CFURLRef baseURL = (CFURLRef) NSURL alloc initFileURLWithPath:sndpath;AudioServicesCreateSystemSoundID (baseURL, &pmph);AudioServicesPlaySystemSound(pmph);baseURL release;retain和copy的区别原来简单解释过属性定义(Property) ,并且提起了简单的retain,copy,assign的区别。那究竟是有什么区别呢?assign就不用说了,因为基本上是为简单数据类型准备的,而不是NS对象们。Retain vs. Copy! copy: 建立一个索引计数为1的对象,然后释放旧对象retain:释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1那上面的是什么该死的意思呢?Copy其实是建立了一个相同的对象,而retain不是:比如一个NSString对象,地址为01111,内容为”STR”Copy到另外一个NSString之后,地址为02222,内容相同,新的对象retain为1,旧有对象没有变化retain到另外一个NSString之后,地址相同(建立一个指针,指针拷贝),内容当然相同,这个对象的retain值+1也就是说,retain是指针拷贝,copy是内容拷贝。哇,比想象的简单多了线程1. 创建一个新的线程: NSThread detachNewThreadSelector:selector(myMethod) toTarget:self withObject:nil;2. 创建线程所调用的方法: - (void)myMethod NSAutoreleasePool *pool = NSAutoreleasePool alloc init; * code that should be run in the new thread goes here * pool release;假如我们需要在线程里面调用主线程的方法函数,就可以用performSelectorOnMainThread来实现: self performSelectorOnMainThread:selector(myMethod) withObject:nil waitUntilDone:false;读取crash的日记文件假如很不幸,我们的某处代码引起了crash,那么就可以阅读这篇文章应该会有用: navigate here 测试1. 在模拟器里,点击 Hardware Simulate Memory Warning to test. 那么我们整个程序每个页面就都能够支持这个功能了。2. Be sure to test your app in Airplane Mode.Access properties/methods in other classesOne way to do this is via the AppDelegate: myAppDelegate *appDelegate = (myAppDelegate *)UIApplication sharedApplication delegate;appDelegate rootViewController flipsideViewController myMethod;创建随机数调用arc4random()来创建随机数. 还可以通过random()来创建, 但是必须要手动的设置seed跟系统时钟绑定。这样才能够确保每次得到的值不一样。所以相比较而言arc4random()更好一点。 定时器下面的这个定时器会每分钟调用一次调用myMethod。 NSTimer scheduledTimerWithTimeInterval:1 target:self selector:selector(myMethod) userInfo:nil repeats:YES;当我们需要给定时器的处理函数myMethod传参数的时候怎么办?用userInfo属性。 1. 首先创建一个定时器: NSTimer scheduledTimerWithTimeInterval:1 target:self selector:selector(myMethod) userInfo:myObject repeats:YES;2. 然后传递NSTimer对象到处理函数: -(void)myMethod:(NSTimer*)timer / Now I can access all the properties and methods of myObjecttimer userInfo myObjectMethod;用invalidate来停止定时器: myTimer invalidate;myTimer = nil; / ensures we never invalidate an already invalid Timer应用分析当应用程序发布版本的时候,我们可能会需要收集一些数据,比如说程序被使用的频率如何。这个时候大多数的人使用PinchMedia来实现。他们会提供我们可以很方便的加到程序里面的Obj-C代码,然后就可以通过他们的网站来查看统计数据。 TimeCalculate the passage of time by using CFAbsoluteTimeGetCurrent(). CFAbsoluteTime myCurrentTime = CFAbsoluteTimeGetCurrent();/ perform calculations here警告窗口显示一个简单的带OK按钮的警告窗口。 UIAlertView *alert = UIAlertView alloc initWithTitle:nil message:An Alert! delegate:self cancelButtonTitle:OK otherButtonTitles:nil;alert show;alert release;Plist文件应用程序特定的plist文件可以被保存到app bundle的Resources文件夹。当应用程序运行起来的时候,就会去检查是不是有一个plist文件在用户的Documents文件夹下。假如没有的话,就会从app bundle目录下拷贝过来。 / Look in Documents for an existing plist fileNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectory = paths objectAtIndex:0;myPlistPath = documentsDirectory stringByAppendingPathComponent: NSString stringWithFormat: %.plist, plistName ;myPlistPath retain;/ If its not there, copy it from the bundleNSFileManager *fileManger = NSFileManager defaultManager;if ( !fileManger fileExistsAtPath:myPlistPath ) NSString *pathToSettingsInBundle = NSBundle mainBundle pathForResource:plistName ofType:plist;现在我们就可以从Documents文件夹去读plist文件了。 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);NSString *documentsDirectoryPath = paths objectAtIndex:0;NSString *path = documentsDirectoryPath stringByAppendingPathComponent:myApp.plist;NSMutableDictionary *plist = NSDictionary dictionaryWithContentsOfFile: path;Now read and set key/values myKey = (int)plist valueForKey:myKey intValue;myKey2 = (bool)plist valueForKey:myKey2 boolValue;plist setValue:myKey forKey:myKey;plist writeToFile:path atomically:YES;Info button为了更方便End-User去按,我们可以增大Info button上可以触摸的区域。 CGRect newInfoButtonRect = CGRectMake(infoButton.frame.origin.x-25, infoButton.frame.origin.y-25, infoButton.frame.size.width+50, infoButton.frame.size.height+50);infoButton setFrame:newInfoButtonRect;查找Subviews(Detecting Subviews)我们可以通过循环来查找一个已经存在的View。当我们使用view的tag属性的话,就很方便实现Detect Subviews。 for (UIImageView *anImage in self.view subviews) if (anImage.tag = 1) / do something手册文档 Official Apple How-Tos Learn Objective-C NSString NSarray 枚举/* NSString */ /一、NSString /*-创建字符串的方法-*/ /1、创建常量字符串。 NSString *astring = This is a String!; /2、创建空字符串,给予赋值。 NSString *astring = NSString alloc init; astring = This is a String!; astring release; NSLog(astring:%,astring); /3、在以上方法中,提升速度:initWithString方法 NSString *astring = NSString alloc initWithString:This is a String!; NSLog(astring:%,astring); astring release; /4、用标准c创建字符串:initWithCString方法 char *Cstring = This is a String!; NSString *astring = NSString alloc initWithCString:Cstring; NSLog(astring:%,astring); astring release; /5、创建格式化字符串:占位符(由一个%加一个字符组成) int i = 1; int j = 2; NSString *astring = NSString alloc initWithString:NSString stringWithFormat:%d.This is %i string!,i,j; NSLog(astring:%,astring); astring release; /6、创建临时字符串 NSString *astring; astring = NSString stringWithCString:This is a temporary string; NSLog(astring:%,astring); /*-从文件读取字符串:initWithContentsOfFile方法-*/ NSString *path = astring.text; NSString *astring = NSString alloc initWithContentsOfFile:path; NSLog(astring:%,astring); astring release; /*-写字符串到文件:writeToFile方法-*/ NSString *astring = NSString alloc initWithString:This is a String!; NSLog(astring:%,astring); NSString *path = astring.text; astring writeToFile: path atomically: YES; astring release; /*-比较两个字符串-*/ /用C比较:strcmp函数 char string1 = string!; char string2 = string!; if(strcmp(string1, string2) = = 0) NSLog(1); /isEqualToString方法 NSString *astring01 = This is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 isEqualToString:astring02; NSLog(result:%d,result); /compare方法(comparer返回的三种值) NSString *astring01 = This is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 compare:astring02 = = NSOrderedSame; NSLog(result:%d,result); /NSOrderedSame判断两者内容是否相同 NSString *astring01 = This is a String!; NSString *astring02 = this is a String!; BOOL result = astring01 compare:astring02 = = NSOrderedAscending; NSLog(result:%d,result); /NSOrderedAscending判断两对象值的大小(按字母顺序进行比较,astring02大于astring01为真) NSString *astring01 = this is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 compare:astring02 = = NSOrderedDescending; NSLog(result:%d,result); /NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真) /不考虑大小写比较字符串1 NSString *astring01 = this is a String!; NSString *astring02 = This is a String!; BOOL result = astring01 caseInsensitiveCompare:astring02 = = NSOrderedSame; NSLog(result:%d,result); /NSOrderedDescending判断两对象值的大小(按字母顺序进行比较,astring02小于astring01为真) /不考虑大小写比较字符串2 NSString *astring01 =

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论