iOS 开发百问(7)

黄舟
Release: 2023-03-05 06:40:01
Original
1399 people have browsed it

71、如何让UIWebView的大小符合HTML的内容?
在iOS5中,这很简单,设置webview的委托,然后在委托中实现didFinishLoad:方法:

-(void)webViewDidFinishLoad:(UIWebView*)webView{
CGSizesize=webView.scrollView.contentSize;//iOS5+
webView.bounds=CGRectMake(0,0,size.width,size.height);
}
Copy after login

72、窗口中有多个Responder,如何快速释放键盘
[[UIApplicationsharedApplication]sendAction:@selector(resignFirstResponder)to:nilfrom:nilforEvent:nil];
这样,可以一次性让所有Responder的失去焦点。
73、如何让UIWebView能通过“捏合”手势进行缩放?
使用如下代码:

webview=[[UIWebViewalloc]init];
webview.autoresizingMask=(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight);
webview.scalesPageToFit=YES;
webview.multipleTouchEnabled=YES;
webview.userInteractionEnabled=YES;
Copy after login

74、Undefinedsymbols:_kCGImageSourceShouldCache、_CGImageSourceCreateWithData、_CGImageSourceCreateImageAtIndex

没有导入ImageIO.framework。

75、expectedmethodtoreaddictionaryelementnotfoundonobjectoftypensdictionary

SDK6.0开始对字典增加了“下标”索引,即通过dictionary[@"key"]的方式检索字典中的对象。但在SDK5.0中,这是非法的。你可以在项目中新建一个头文件NSObject+subscripts.h来解决这个问题,内容如下:

#if__IPHONE_OS_VERSION_MAX_ALLOWED<60000
@interfaceNSDictionary(subscripts)
-(id)objectForKeyedSubscript:(id)key;
@end
@interfaceNSMutableDictionary(subscripts)
-(void)setObject:(id)objforKeyedSubscript:(id)key;
@end
@interfaceNSArray(subscripts)
-(id)objectAtIndexedSubscript:(NSUInteger)idx;
@end
@interfaceNSMutableArray(subscripts)
-(void)setObject:(id)objatIndexedSubscript:(NSUInteger)idx;
@end
#endif
Copy after login

76、错误:-[MKNetworkEnginefreezeOperations]:messagesenttodeallocatedinstance0x1efd4750
这是一个内存管理错误。MKNetwork框架支持ARC,本来不应该出现内存管理问题,但由于MKNetwork中的一些Bug,导致在MKNetworkEngine不被设置为strong属性时出现该问题。建议MKNetworkEngine对象设置为ViewController的strong属性。

77、UIImagePickerControllerSourceTypeSavedPhotosAlbum和UIImagePickerControllerSourceTypePhotoLibrary的区别
UIImagePickerControllerSourceTypePhotoLibrary表示整个照片库,允许用户选择所有的相册(包括相机胶卷),而UIImagePickerControllerSourceTypeSavedPhotosAlbum仅包括相机胶卷。
78、警告“Prototypetablecellsmusthaveresueidentifiers”
Prototypecell(iOS5模板单元格)的Identidfier属性未填写,在属性模板中填写即可。
79、如何读取info.plist中的值?
以下示例代码读取了info.plist中的URLSchemes:

//TheInfo.plistisconsideredthemainBundle.
mainBundle=[NSBundlemainBundle];
NSArray*types=[mainBundleobjectForInfoDictionaryKey:@"CFBundleURLTypes"];
NSDictionary*dictionary=[typesobjectAtIndex:0];
NSArray*schemes=[dictionaryobjectForKey:@"CFBundleURLSchemes"];
NSLog(@"%@",[schemesobjectAtIndex:0]);
Copy after login

80、如何让AtionSheet不自动解散?
UIActionSheet无论点击什么按钮,最终都会自动解散。最好的办法是子类化它,增加一个noAutoDismiss属性并覆盖dismissWithClickedButtonIndex方法,当此属性为YES时,不进行解散动作,为NO时调用默认的dismissWithClickedButtonIndex:

#import
@interfaceMyAlertView:UIAlertView
@property(nonatomic,assign)BOOLnoAutoDismiss;
@end
#import"MyAlertView.h"
@implementationMyAlertView
-(void)dismissWithClickedButtonIndex:(NSInteger)buttonIndexanimated:(BOOL)animated{
if(self.noAutoDismiss)
return;
[superdismissWithClickedButtonIndex:buttonIndexanimated:animated];
}
@end
Copy after login

81、在执行RSA_public_encrypt函数时崩溃
这个问题很奇怪。使用两台设备,一台系统为6.1,一台系统为6.02,同样的代码在6.02版本中一切正常,在6.1版本中导致程序崩溃:

unsignedcharbuff[2560]={0};
intbuffSize=0;
buffSize=RSA_public_encrypt(strlen(cleartext),
(unsignedchar*)cleartext,buff,rsa,padding);
Copy after login

问题在于这一句:

buffSize=RSA_public_encrypt(strlen(cleartext),
(unsignedchar*)cleartext,buff,rsa,padding);
Copy after login

6.1系统iPad为3G版,由于使用的3G网络(联通3gnet)信号不稳定,导致rsa公钥经常性取不到,故rsa参数出现nil。而6.0系统iPad为wifi版,信号稳定,故无此问题。解决方法是检查rsa参数的有效性。
82、警告:UITextAlignmentCenterisdeprecatediniOS6
NSTextAlignmentCenter已经被UITextAlignmentCenter所替代。类似的替代还有一些,你可以使用以下宏:

#ifdef__IPHONE_6_0//iOS6andlater
#defineUITextAlignmentCenter(UITextAlignment)NSTextAlignmentCenter
#defineUITextAlignmentLeft(UITextAlignment)NSTextAlignmentLeft
#defineUITextAlignmentRight(UITextAlignment)NSTextAlignmentRight
#defineUILineBreakModeTailTruncation(UILineBreakMode)NSLineBreakByTruncatingTail
#defineUILineBreakModeMiddleTruncation(UILineBreakMode)NSLineBreakByTruncatingMiddle
#endif
Copy after login

83、Xcode5中无法设置-fno-objc-arc
Xcode5默认使用ARC,同时隐藏了CompileSources中的“CompilerFlags”列,因此你无法设置.m文件的-fno-objc-arc选项。要显示.m文件的CompilerFlags列,你可以使用菜单“View->Utilities->HideUtilities”来暂时关闭右侧的Utilities窗口,以显示CompilerFlags列,这样你就可以设置.m文件的-fno-objc-arc标志。
84、警告:‘ABAddressBookCreate'isdeprecated:firstdeprecatediniOS6.0
iOS6.0以后该方法被抛弃,用ABAddressBookCreateWithOptions方法替代:

CFErrorRef*error=nil;
ABAddressBookRefaddressBook=ABAddressBookCreateWithOptions(NULL,error);
Copy after login

85、iOS6.0以后如何读取手机通讯录?
iOS6以后,AddressBook框架发生了改变,尤其是app访问手机通讯录需要获得用户授权。因此,除了需要使用新的ABAddressBookCreateWithOptions初始化方法之外,我们还需要使用AddressBook框架新的ABAddressBookRequestAccessWithCompletion方法,用以获知用户是否授权:

+(void)fetchContacts:(void(^)(NSArray*contacts))successfailure:(void(^)(NSError*error))failure{
#ifdef__IPHONE_6_0
if(ABAddressBookRequestAccessWithCompletion){
CFErrorReferr;
ABAddressBookRefaddressBook=ABAddressBookCreateWithOptions(NULL,&err);
ABAddressBookRequestAccessWithCompletion(addressBook,^(boolgranted,CFErrorReferror){
//ABAddressBookdoesn'tgauranteeexecutionofthisblockonmainthread,butwewantourcallbackstobe
dispatch_async(dispatch_get_main_queue(),^{
if(!granted){
failure((__bridgeNSError*)error);
}else{
readAddressBookContacts(addressBook,success);
}
CFRelease(addressBook);
});
});
}
#else
//oniOS<6
ABAddressBookRefaddressBook=ABAddressBookCreate();
readAddressBookContacts(addressBook,success);
CFRelease(addressBook);
}
#endif
}
Copy after login

这个方法有两个块参数success和failure,分别用于执行用户授权访问的两种情况:同意和不同意。
在代码调用ABAddressBookRequestAccessWithCompletion函数时,第2个参数是一个块,该块的granted参数用于告知用户是否同意。如果granted为No(不同意),我们调用failure块。如果granted为Yes(同意),我们将调用readAddressBookContacts函数,进一步读取联系人信息。
readAddressBookContacts声明如下:

staticvoidreadAddressBookContacts(ABAddressBookRefaddressBook,void(^completion)(NSArray*contacts)){
//dostuffwithaddressBook
NSArray*contacts=(NSArray*)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
completion(contacts);
}
Copy after login

首先从addressBook中获取所有联系人(结果放到一个NSArray数组中),然后调用completion块(即fetchContacts方法的success块)。在completion中我们可以对数组进行迭代。
一个调用fetchContacts方法的例子:

+(void)getAddressBook:(void(^)(NSArray*))completion{
[selffetchContacts:^(NSArray*contacts){
NSArray*sortedArray=[contactssortedArrayUsingComparator:^(ida,idb){
NSString*fullName1=(NSString*)CFBridgingRelease(ABRecordCopyCompositeName((__bridgeABRecordRef)(a)));
NSString*fullName2=(NSString*)CFBridgingRelease(ABRecordCopyCompositeName((__bridgeABRecordRef)(b)));
intlen=[fullName1length]>[fullName2length]?[fullName2length]:[fullName1length];
NSLocale*local=[[NSLocalealloc]initWithLocaleIdentifier:@"zh_hans"];
return[fullName1compare:fullName2options:NSCaseInsensitiveSearchrange:NSMakeRange(0,len)locale:local];
}];
completion(sortedArray);
}failure:^(NSError*error){
DLog(@"%@",error);
}];
}
Copy after login

即在fetchContacts的完成块中对联系人姓名进行中文排序。最后调用completion块。在fetchContacts的错误块中,简单打印错误信息。
调用getAddressBook的示例代码如下:

[AddressBookHelpergetAddressBook:^(NSArray*node){
NSLog(@"%@",NSArray);
}];
Copy after login

86、ARC警告:PerformSelectormaycausealeakbecauseitsselectorisunknown
这个是ARC下特有的警告,用#pragmaclangdiagnostic宏简单地忽略它即可:

#pragmaclangdiagnosticpush
#pragmaclangdiagnosticignored"-Warc-performSelector-leaks"
[targetperformSelector:selwithObject:[NSNumbernumberWithBool:YES]];
#pragmaclangdiagnosticpop
Copy after login

87、'libxml/HTMLparser.h'filenotfound
导入libxml2.dylib后出现此错误,尤其是使用ASIHTTP框架的时候。在BuildSettings的HeaderSearchPaths列表中增加“${SDK_DIR}/usr/include/libxml2”一项可解决此问题。
所谓"$(SDK_ROOT)"是指编译目标所使用的SDK的目录,以iPhoneSDK7.0(真机)为例,是指/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk目录。
注意,似乎Xcode4.6以后“UserHeaderSearchPaths”(或者“AlwaysSearchUserPaths”)不再有效,因此在“UserHeaderSearchPaths”中配置路径往往是无用的,最好是配置在“HeaderSearchPaths”中。
88、错误:-[UITableViewdequeueReusableCellWithIdentifier:forIndexPath:]:unrecognizedselector
这是SDK6以后的方法,在iOS5.0中这个方法为:
[UITableViewdequeueReusableCellWithIdentifier:]
89、@YES语法在iOS5中无效,提示错误:Unexpectedtypename'BOOL':expectedexpression

在IOS6中,@YES定义为:
#defineYES((BOOL)1)
但在iOS5中,@YES被少写了一个括号:
#defineYES(BOOL)1
因此@YES在iOS5中的正确写法应当为@(YES)。为了简便,你也可以在.pch文件中修正这个Bug:

#if__has_feature(objc_bool)
#undefYES
#undefNO
#defineYES__objc_yes
#defineNO__objc_no
#endif
Copy after login

以上就是iOS 开发百问(7)的内容,更多相关内容请关注PHP中文网(www.php.cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!