首頁  >  文章  >  後端開發  >  iOS 開發百問(7)

iOS 開發百問(7)

黄舟
黄舟原創
2017-01-20 09:41:151501瀏覽

71、如何讓UIWebView的大小符合HTML的內容?
在iOS5中,這很簡單,設定webview的委託,然後在委託中實作didFinishLoad:方法:

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

72、視窗中有多個Responder,如何快速釋放鍵盤
[[UIApplicationsharedApplication]sendAction: resignFirstResponder)to:nilfrom:nilforEvent:nil];
這樣,可以一次讓所有Responder的失去焦點。
73、如何讓UIWebView能透過「捏合」手勢進行縮放?
使用以下程式碼:

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

74、Undefinedsymbols:_kCGImageSourceShouldCache、_CGImageSourceCreateWithData、_CGImageSourceCreateImageAtIndex

沒有導入mage

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<NSCopying>)key;
@end
@interfaceNSArray(subscripts)
-(id)objectAtIndexedSubscript:(NSUInteger)idx;
@end
@interfaceNSMutableArray(subscripts)
-(void)setObject:(id)objatIndexedSubscript:(NSUInteger)idx;
@end
#endif

76、錯誤:-[MKNetworkEnginefreezeOperations]:messagesenttodeallocatedinstance0x1efd4750
這是一個記憶體管理錯誤記憶體。 MKNetwork框架支援ARC,本來不應該出現記憶體管理問題,但由於MKNetwork中的一些Bug,導致在MKNetworkEngine不被設定為strong屬性時出現該問題。建議MKNetworkEngine物件設定為ViewController的strong屬性。

77、UIImagePickerControllerSourceTypeSavedPhotosAlbum和UIImagePickerControllerSourceTypePhotoLibrary的差異
UIImagePickerControllerSourceTypePhotoLibrary表示整個照片庫,讓使用者可以選擇所有的相簿(包括相機膠卷),而相機膠卷。
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]);

80、如何讓AtionSheet不自動解散?
UIActionSheet無論點擊什麼按鈕,最終都會自動解散。最好的方法是子類化它,增加一個noAutoDismiss屬性並覆蓋dismissWithClickedButtonIndex方法,當此屬性為YES時,不進行解散動作,為NO時調用預設的dismissWithClickedButtonIndex:

#import<UIKit/UIKit.h>
@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

81、在執行函數時在執行時。崩潰
這個問題很奇怪。使用兩台設備,一台系統為6.1,一台系統為6.02,同樣的程式碼在6.02版本中一切正常,在6.1版本中導致程式崩潰:

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

問題在於這句話:

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

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

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);

85以後如何讀取手機通訊錄?
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&#39;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
}

這個方法有兩個區塊參數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);
}

首先從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);
}];
}

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

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

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

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

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

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

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn