`
wangpengfei360
  • 浏览: 1058271 次
文章分类
社区版块
存档分类
最新评论

Some Tips In Object C

 
阅读更多

1.使用class获得meta class

NSLog(@"Class name: %@",[[[arr objectAtIndex:i] class] description]);

2.使用NSClassFromString和 NSSelectorFromString

id object=[[NSClassFromString(@"NameofClass") alloc] init];//NSClassFromString加载的类不需要importSEL sel = NSSelectorFromString(@"doSomethingMethod:")//注意这个冒号,说明方法带有参数

if([object respondsToSelector:sel]){

[object performSelector:sel withObject:color];//注意如果有两个参数,使用两个withObject:参数;

}

3.使用isa

id movie=[arrFavorite objectAtIndex:row];

if (movie->isa ==[IndexPageItem class]) {

NSLog(@"movie title:%@",[movie description]);

}

4.谓词

NSArray* arr=[NSArray arrayWithObjects:@"1",@"0",@"no",@"NO",@"YES",@"yes",nil];

NSPredicate* predicate=[NSPredicate predicateWithFormat:

@"SELF IN{'0','no','NO'}"];

NSArray* result=[arr filteredArrayUsingPredicate:predicate];

NSLog(@"%@",result);

for (NSString* s in arr){

NSLog(@"%@:%d",s,[predicate evaluateWithObject:s]);

}

5. From NSString to NSData

NSString *text = @"Some string";

NSData *data = [text dataUsingEncoding:NSUTF8StringEncoding];

6. From NSData to NSString

NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

7.日期和时间

NSCalendar *gregorian=[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents* todayComponents=[gregorian components:(NSDayCalendarUnit|NSMonthCalendarUnit|NSYearCalendarUnit) yourDate];

NSInteger theDay =[todayComponents day];

NSInteger theMonth =[todayComponents month];

NSInteger theYear =[todayComponents year];

// now build a NSDate object for yourDate using these components

NSDateComponents *components =[[NSDateComponents alloc] init];

[components setDay:theDay];

[components setMonth:theMonth];

[components setYear:theYear];

NSDate *thisDate =[gregorian dateFromComponents:components];

[components release];

// now build a NSDate object for the next day

NSDateComponents *offsetComponents =[[NSDateComponents alloc] init];

[offsetComponents setDay:1];

NSDate *nextDate =[gregorian dateByAddingComponents:offsetComponents toDate: yourDate options:0];

[offsetComponents release];

[gregorian release];

8.使用performSelectorInBackground(多线程)调用的方法,必须在该方法中NSAutoreleasePool

否则出现错误:no pool in place - just leaking。如果用performSelector则没有这个问题。

9.ld: symbol(s) not found 错误的解决办法

展开"Targets-->Compile Sources",查看列出的所有.m文件,找出其中缺失的.m文件,拖到其中。

10.Ojbect C让线程休眠

[NSThread sleepForTimeInterval:2];//单位是秒

11.nil和NULL的区别

在Object C中,NULL和nil都是空指针,不同的是,NULL用于c 指针,即(void *);而nil用于c++或java对象,即id为空


12.字符串替换

str=[str stringByReplacingOccurrencesOfString:@"[]" withString:@""];


13.assign,copy,retain之间的区别

  • assign: 简单赋值,不更改索引计数(Reference Counting)。
  • copy: 建立一个索引计数为1的对象,然后释放旧对象
  • retain:释放旧的对象,将旧对象的值赋予输入对象,再提高输入对象的索引计数为1

retain的实际语法为:

- (void)setName:(NSString *)newName {

if (name != newName) {

[name release];

name = [newName retain];

// name’s retain count has been bumped up by 1

}

}

说了那么麻烦,其实接下来的话最重要:

?如果你不懂怎么使用他们,那么就这样 ->

  • 使用assign: 对基础数据类型 (NSInteger,CGFloat)和C数据类型(int, float, double, char, 等等)
  • 使用copy: 对NSString
  • 使用retain: 对其他NSObject和其子类

14.nonatomic关键字:

atomic是Objc使用的一种线程保护技术,基本上来讲,是防止在写未完成的时候被另外一个线程读取,造成数据错误。而这种机制是耗费系统资源的,所以在iPhone这种小型设备上,如果没有使用多线程间的通讯编程,那么nonatomic是一个非常好的选择。

15.发送短信/邮件/打电话


+ (void)alert:(NSString *)msg
{
UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle:msg message:@"" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] autorelease];
[alertView showWithBackground];
}

+ (NSString*) cleanPhoneNumber:(NSString*)phoneNumber
{
NSString* number = [NSString stringWithString:phoneNumber];
NSString* number1 = [[[number stringByReplacingOccurrencesOfString:@" " withString:@""]
//stringByReplacingOccurrencesOfString:@"-" withString:@""]
stringByReplacingOccurrencesOfString:@"(" withString:@""]
stringByReplacingOccurrencesOfString:@")" withString:@""];

return number1;
}

+ (void) makeCall:(NSString *)phoneNumber
{
if ([DeviceDetection isIPodTouch]){
[UIUtils alert:kCallNotSupportOnIPod];
return;
}

NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];

NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@", numberAfterClear]];
NSLog(@"make call, URL=%@", phoneNumberURL);

[[UIApplication sharedApplication] openURL:phoneNumberURL];
}

+ (void) sendSms:(NSString *)phoneNumber
{
if ([DeviceDetection isIPodTouch]){
[UIUtils alert:kSmsNotSupportOnIPod];
return;
}

NSString* numberAfterClear = [UIUtils cleanPhoneNumber:phoneNumber];

NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"sms:%@", numberAfterClear]];
NSLog(@"send sms, URL=%@", phoneNumberURL);
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}

+ (void) sendEmail:(NSString *)phoneNumber
{
NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:@"mailto:%@", phoneNumber]];
NSLog(@"send sms, URL=%@", phoneNumberURL);
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}

+ (void) sendEmail:(NSString *)to cc:(NSString*)cc subject:(NSString*)subject body:(NSString*)body
{
NSString* str = [NSString stringWithFormat:@"mailto:%@?cc=%@&subject=%@&body=%@",
to, cc, subject, body];

str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];

}
16.NSString转换编码gb2312
NSURL *url=[NSURL URLWithString:urlStr];
NSData *data=[NSData dataWithContentsOfURL:url]; NSStringEncoding enc =CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000); NSString *retStr =[[NSString alloc]initWithData:data encoding:enc];

17.将指定格式的字符串转换为日期类型
//yyyyMMddHHmmss格式的字符串转换为NSDate类型
-(NSDate*)stringToDate:(NSString*)dateString{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyyMMddHHmmss"];
NSDate *date = [dateFormatter dateFromString:dateString];
[dateFormatter release];
return date;}
18."Array was mutated while being enumerated"问题的解决
在操作数组对象时进行同步,如:@synchronized(enemiesArray) {
⋯⋯
数组操作代码
⋯⋯}
19、字符串与数组之间的转换:SString *string=@"one:two:three:four"; NSArray *result=[string componentsSeparatedByString:@":"]; string=[result componentsJoinedByString:@"_"]; 20、定时器NSTimer//1秒后,触发定时器事件
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self 
selector:@selector(timerFired) userInfo:nil repeats:NO];
21、让UITextField里面的text垂直居中可以这样写:
text.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

22、在UITextField最右侧加图片是以下代码,
UIImageView *imgv=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"right.png"]];
text.rightView=imgv;
text.rightViewMode = UITextFieldViewModeAlways; 
如果是在最左侧加图片就换成:
text.leftView=imgv;
text.leftViewMode = UITextFieldViewModeAlways; 

23、NSLog 的格式化字符串
%@ 对象
%% 百分号
%d, %i 整数
%u 无符整形
%f 浮点/双字
%x, %X 二进制整数
%o 八进制整数
%zu size_t
%p 指针
%e 浮点/双字 (科学计算)
%g 浮点/双字 
%s C 字符串
%.*s Pascal字符串
%c 字符
%C unichar
%lld 64位长整数(long long)
%llu 无符64位长整数
%Lf 64位双字

24、直接链接到itunes

NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/us/album/esperanza/id321585893"];

[[UIApplication sharedApplication] openURL:url];

直接链接到safari网页

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];

25、获取Bundle的版本号

NSString* localVersion= [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];

26、stray '\357' in program

错把'['写成中文的方括号'['了。

27、provisioning profile 'xxx' can't be found

如果你更新了profile,再编译iphone项目,发现下面的错误,那你无论如何clean也不会成功,那真是让人恼火阿

这时候,先copy上面那行出错信息中的profile identifier,比如:86C90BA7-77B6-4A75-9EAD-A1FD88C17F6D

然后关闭这个项目,打开finder到你的项目文件xxxx.xcodeproj上面按鼠标右键,选择Show Package Contents菜单。

在新打开的finder的,找到project.pbxproj,使用一个文本edit打开它,用查找功能找到所有的有那行编码的位置,删除那一行:

"PROVISIONING_PROFILE[sdk=iphoneos*]" = "86C90BA7-77B6-4A75-9EAD-A1FD88C17F6D";

删除以后,保存这个 project.pbxproj 文件,用xcode重新打开你的项目,再编译一下试试

28、获取设备类型及当前方向

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){// 如果设备为iPad //获取设备当前方向,及时进行旋屏 UIInterfaceOrientation orientation=[[UIDevice currentDevice] orientation]; [self willAnimateRotationToInterfaceOrientation:orientation duration:0]; }

29、打印UIView的subviews

- (void)explode:(id)aView level:(int)aLevel { for (int i = 0; i <aLevel; i++) printf("-"); printf("%s:%s\n",[[[aView class] description] UTF8String],[[[aView superclass] description] UTF8String]); for(UIView *subview in [aView subviews]) [self explode:subview level:(aLevel + 1)]; }

使用:[self explode:textview level:0];

30、旋屏后20像素bug的解决

没有优雅的解决方案,只有在view显示后,手动调整:

mainView.frame=CGRectMake(0, 0 - 20, self.view.frame.size.width, self.view.frame.size.height + 20);

31、安装Xcode3.2后安装Xcode4.2出现错误:error: unable to create '/Users/km-cn/Library/Developer/Xcode/DerivedData/MOA-dwztpffnaapnqfevxsfxemqawqdi/Build/Intermediates' (Permission denied) 使用chmod命令:sudo chmod -R 777 /Users/km-cn/Library/Developer/ 32、'UIKeyboardBoundsUserInfoKey' is deprecated警告

将:NSValue* aValue = [infoobjectForKey:UIKeyboardBoundsUserInfoKey];

修改为:NSValue* aValue = [info objectForKey:@"UIKeyboardBoundsUserInfoKey"];

32、退出程序

exit(EXIT_SUCCESS); abort();

这个是undocument的,随时可能不可用。

33、 'UIKeyboardBoundsUserInfoKey' is deprecated
简单地用
NSValue *value = [info objectForKey:@"UIKeyboardBoundsUserInfoKey"];
替换掉:
NSValue *value = [info objectForKey:UIKeyboardBoundsUserInfoKey];

34、缩放网页内容以适应UIWebView
NSString *jsCommand = [NSString stringWithFormat:@"document.body.style.zoom = 0.40;"];
[webView stringByEvaluatingJavaScriptFromString:jsCommand];

或者
webView.scalesPageToFit=YES;
两个方法只能选择其中之一,前者不支持多点触摸缩放,后者支持——但它的自适应缩放不是很好,看起来页面总是要比屏幕真实尺寸要小一点,解决办法是,在html页面中加入:
<
metaname="viewport"content="width=320"/>

35、使TextField被编辑时,键盘不弹出
设置Text Field的delegate,同时实现UITextFieldDelegate中的textFieldDidBeginEditing方法,并在其中加入[textField resignFirstResponder ]。
如果是Text View,要实现UITextViewDelegate中的textViewDidBeginEditing方法。
36、定义常量
声明(类声明以外):extern NSString * const kInitURL;
定义(类实现以外):NSString * const kInitURL = @"http://marshal.easymorse.com";
37、freeform size not available
打开报错的该 .xib 文件。点击工具面板中的File Inspector面板。找到“Interface Builder Document->Document Versioning->Development”,将值改为Xcode4.2。

38、把C结构体封装到O-C数组

结构体->NSData:
CGSize imageSize = currentImg.size;
NSData *pointObjectIn = [NSData dataWithBytes:&imageSize length:sizeof(CGSize)];
[persistentArray addObject:pointObjectIn];

NSData->结构体
NSData* getImgeData = [arrayImageCGSize objectAtIndex:i] ;
CGSize imageSize = *(CGSize*)[getImgeData bytes];

39、用objc_msgSend调用方法
首先,导入<objc/message.h>

objc_msgSend(object, @selector(foo:bar:err:), var, var2, errVar);
如果参数中有简单类型(int,float)或者结构体,需要进行转换,比如:
objc_msgSend(..., *(int*)&var, ...)

40、stringWithCSString is deprecated
使用
+(id)stringWithCString:(const char *)cString encoding:(NSStringEncoding)enc代替
 41、NSLog使用技巧
NSLog(@"%s %d %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);

输出 文件名, 行号, 函数名

__FUNCTION__是C++风格的, __PRETTY_FUNCTION__ 是更容易人理解的, 在cocoa中二者是一样的。
42、frame 的各个点的坐标
frame.origin - Returns top left corner
center - Returns the center of the view
CGRectGetMinX(frame) - Gets x-coord of left edge.
CGRectGetMinY(frame) - Gets y-coord of top edge.
CGRectGetMidX(frame) - Gets x-coord of center.
CGRectGetMidY(frame) - Gets y-coord of center.
CGRectGetMaxX(frame) - Gets x-coord of right edge.
CGRectGetMaxY(frame) - Gets y-coord of bottom edge.

43、No Packager exists for the type of archive
可能的解决办法(其中之一或全部):
  1. 将每个依赖项目的build settings中的“skip installation”设置为yes;

  2. 将每个依赖项目的build settings中的installation directory属性清空;
  3. 将每个依赖项目的build phases -> copy headers下private和public中的所有头文件拷贝到项目中。


44、Archive时遇到“ResourceRules.plist:cannot read resources”错误
在build settings中找到Code Signing Resource Rules Path,填入 $(SDKROOT)/ResourceRules.plist

分享到:
评论

相关推荐

    c++ standard library practical tips

    Third, Chapter 13 has an application that uses some of the tips in a realistic setting. If the technique you’re interested in is in this chapter, you get to see it in action. Finally, Chapters 1 and...

    Mastering JavaScript Object-Oriented Programming

    We'll use the famous promises to work with asynchronous processes and will give you some tips on how to organize your code effectively. You'll find out how to create robust code using SOLID ...

    Sams Teach Yourself C++ in One Hour a Day (8th Edition).pdf(21天学通C++ 第8版 英文版)

    world C++ applications * Learn how to build effective programs in C++ with hands-on exercises * Get expert tips on implementing C++ in the corporate environment ' Learn on your own time, at your own ...

    Kenneth Reek - Pointers on C

    The author also gives an effective presentation of functions in C, particularly the construction of recursive functions, and he employs some useful diagrams to illustrate how the variables in a ...

    C++ Game Development Cookbook-Packt Publishing

    Chapter 1, Game Development Basics, explains the basics of C++ programming, writing small programs to be used in ...Chapter 13, Tips and Tricks, has some neat tips and tricks of using C++ to make games.

    Thinking in LINQ

    some are also truly helpful in minimizing the total number of code lines. This chapter shows how you can benefit from using MoreLINQ. • Chapter 6: Creating Domain-Specific Languages Using LINQ Domain...

    JavaScript Functional Programming for JavaScript Developers (PDF, EPUB, MOBI)

    This course will begin with providing insights and practical tips on advanced JavaScript features to build highly scalable web and mobile system and move on to some design patterns with JavaScript....

    Learn Functional programmming with Elixir

    If you're already an Elixir or functional programming expert, you may find some valuable tips here, but this book probably isn't for you. What's in This Book? You'll find a beginner's guide to ...

    Mastering.OpenCV.Android.Application.Programming.1783988207

    The book ends with a short chapter covering useful Android tips and tricks and some common errors and solutions that people might face while building an application. By the end of the book, readers ...

    Learn iPhone and iPad Cocos2D Game Development

    It is assumed that the reader will have some knowledge of object-oriented programming and the Apple and iPhone/iPad developer environment. amazon link:...

    Tkinter GUI Application Development HOTSHOT(PACKT,2013)

    Finally, you are provided with tips for writing reusable, scalable, and quality GUI code for larger projects. The appendices provide a quick reference sheet for Tkinter. What you will learn from this...

    精通Android 4 游戏开发(Advanced.Android.4.Games)

    By combining the elegant object-oriented features of Java and the raw power of C, there is no limit to the types of games that you can build for the platform, such as the “Quake 3D”-like game app ...

    The JavaScript Pocket Guide

    JavaScript is an object-oriented scripting language that enables you to modify a document’s structure, styling, and content in response to user actions. This handy pocket serves as both a quick ...

    Troubleshooting.Xcode.14842156

    Learn how to use C to workaround some Objective-C limitations. Who this book is for iOS and OS X developers who need to troubleshoot problems and limitations with Xcode. Developers with all levels of ...

    Troubleshooting.Xcode.1484215613

    Learn how to use C to workaround some Objective-C limitations. Who this book is for iOS and OS X developers who need to troubleshoot problems and limitations with Xcode. Developers with all levels of ...

    Apress.Advanced.Android.4.Games.Jan.2012

    By combining the elegant object-oriented features of Java and the raw power of C, there is no limit to the types of games that you can build for the platform, such as the “Quake 3D”-like game app ...

    WPF and Silverlight MVVM

    In Chapter 1, WPF and Silverlight will be explored in some detail and their respective features highlighted. Chapter 2introduces the foundation of the MVVM pattern: the databinding model that ...

    JDBC Developers Guide Reference.rar

    and some scenarios of how you can use them. This chapter also guides you through the basics of testing your installation and configuration. Chapter 3, "Basic Features" This chapter covers the basic ...

    Pro WPF and Silverlight MVVM

    In Chapter 1, WPF and Silverlight will be explored in some detail and their respective features highlighted. Chapter 2 introduces the foundation of the MVVM pattern: the databinding model that ...

Global site tag (gtag.js) - Google Analytics