標籤:style http color io os 使用 ar for strong
71、如何讓UIWebView的大小符合HTML的內容?
在 iOS 5中,這很簡單,設定 webview 的委託,然後在委託中實現didFinishLoad:方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView{
CGSize size=webView.scrollView.contentSize;//iOS 5+
webView.bounds=CGRectMake(0,0,size.width,size.height);
}
72、視窗中有多個Responder,如何快速釋放鍵盤
[[UIApplication sharedApplication] sendAction:@selector(resignFirstResponder) to:nil from:nil forEvent:nil];
這樣,可以一次性讓所有Responder 的失去焦點。
73、如何讓 UIWebView 能通過“捏合”手勢進行縮放?
使用如下代碼:
webview=[[UIWebView alloc]init];
webview.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
webview.scalesPageToFit=YES;
webview.multipleTouchEnabled=YES;
webview.userInteractionEnabled=YES;
74、Undefined symbols:_kCGImageSourceShouldCache、_CGImageSourceCreateWithData、_CGImageSourceCreateImageAtIndex
沒有匯入 ImageIO.framework。
75、 expectedmethod to read dictionary element not found on object of type nsdictionary
SDK 6.0 開始對字典增加了“下標”索引,即通過 dictionary[@"key"] 的方式檢索字典中的對象。但在 SDK 5.0 中,這是非法的。你可以在項目中建立一個標頭檔 NSObject+subscripts.h 來解決這個問題 ,內容如下:
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 60000
@interface NSDictionary(subscripts)
- (id)objectForKeyedSubscript:(id)key;
@end
@interface NSMutableDictionary(subscripts)
- (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key;
@end
@interface NSArray(subscripts)
- (id)objectAtIndexedSubscript:(NSUInteger)idx;
@end
@interface NSMutableArray(subscripts)
- (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)idx;
@end
#endif
76、錯誤:-[MKNetworkEngine freezeOperations]: message sent to deallocated instance0x1efd4750
這是一個記憶體管理錯誤。MKNetwork 架構支援 ARC,本來不應該出現記憶體管理問題,但由於 MKNetwork 中的一些 Bug,導致在 MKNetworkEngine 不被設定為 strong 屬性時出現該問題。建議 MKNetworkEngine 對象設定為 ViewController 的 strong 屬性。
77、UIImagePickerControllerSourceTypeSavedPhotosAlbum和 UIImagePickerControllerSourceTypePhotoLibrary的區別
UIImagePickerControllerSourceTypePhotoLibrary 表示整個照片庫,允許使用者選擇所有的相簿(包括相機菲林),而UIImagePickerControllerSourceTypeSavedPhotosAlbum僅包括相機菲林。
78、警告“Prototype tablecells must have resue identifiers”
Prototype cell(iOS 5 模板儲存格)的 Identidfier 屬性未填寫,在屬性模板中填寫即可。
79、如何讀取 info.plist 中的值?
以下範例程式碼讀取了info.plist 中的 URL Schemes:
// The Info.plist isconsidered the mainBundle.
mainBundle = [NSBundle mainBundle];
NSArray* types=[mainBundle objectForInfoDictionaryKey:@"CFBundleURLTypes"];
NSDictionary* dictionary=[types objectAtIndex:0];
NSArray* schemes=[dictionary objectForKey:@"CFBundleURLSchemes"];
NSLog(@"%@",[schemes objectAtIndex:0]);
80、如何讓 AtionSheet 不自動解散?
UIActionSheet 無論點擊什麼按鈕,最終都會自動解散。最好的辦法是子類化它,增加一個 noAutoDismiss 屬性並覆蓋 dismissWithClickedButtonIndex 方法,當此屬性為 YES 時,不進行解散動作,為NO 時調用預設的 dismissWithClickedButtonIndex:
#import <UIKit/UIKit.h>
@interface MyAlertView : UIAlertView
@property(nonatomic, assign) BOOL noAutoDismiss;
@end
#import "MyAlertView.h"
@implementation MyAlertView
-(void)dismissWithClickedButtonIndex:(NSInteger)buttonIndex animated:(BOOL)animated {
if(self.noAutoDismiss)
return;
[super dismissWithClickedButtonIndex:buttonIndex animated:animated];
}
@end
81、在執行 RSA_public_encrypt函數時崩潰
這個問題很奇怪。使用兩台裝置,一台系統為 6.1,一台系統為 6.02,同樣的代碼在 6.02 版本中一切正常,在 6.1 版本中導致程式崩潰:
unsigned char buff[2560]={0};
int buffSize = 0;
buffSize = RSA_public_encrypt ( strlen(cleartext),
(unsigned char*)cleartext, buff, rsa, padding );
問題在於這一句:
buffSize = RSA_public_encrypt ( strlen(cleartext),
(unsigned char*)cleartext, buff, rsa, padding );
6.1系統iPad為 3G 版,由於使用的 3G 網路(聯通3gnet)訊號不穩定,導致 rsa 公開金鑰經常性取不到,故 rsa 參數出現 nil。而 6.0 系統iPad為wifi 版,訊號穩定,故無此問題。解決方案是檢查 rsa 參數的有效性。
82、警告:UITextAlignmentCenteris deprecated in iOS 6
NSTextAlignmentCenter 已經被 UITextAlignmentCenter 所替代。類似的替代還有一些,你可以使用以下宏:
#ifdef __IPHONE_6_0 // iOS6 and later
# define UITextAlignmentCenter (UITextAlignment)NSTextAlignmentCenter
# define UITextAlignmentLeft (UITextAlignment)NSTextAlignmentLeft
# define UITextAlignmentRight (UITextAlignment)NSTextAlignmentRight
# define UILineBreakModeTailTruncation (UILineBreakMode)NSLineBreakByTruncatingTail
# defineUILineBreakModeMiddleTruncation (UILineBreakMode)NSLineBreakByTruncatingMiddle
#endif
83、Xcode5 中無法設定 -fno-objc-arc
Xcode5 預設使用 ARC,同時隱藏了Compile Sources 中的“ Compiler Flags”列,因此你無法設定 .m 檔案的 -fno-objc-arc 選項。要顯示.m 檔案的 Compiler Flags列,你可以使用菜單 “View->Utilities->Hide Utilities”來暫時關閉右側的 Utilities 視窗,以顯示 Compiler Flags 列,這樣你就可以設定.m檔案的 -fno-objc-arc 標誌。
84、警告:‘ABAddressBookCreate‘is deprecated:first deprecated in iOS 6.0
iOS6.0以後該方法被拋棄,用 ABAddressBookCreateWithOptions方法替代:
CFErrorRef* error=nil;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, error);
85、iOS6.0 以後如何讀取手機通訊錄?
iOS 6以後,AddressBook 架構發生了改變,尤其是app訪問手機通訊錄需要獲得使用者授權。因此,除了需要使用新的ABAddressBookCreateWithOptions 初始化方法之外,我們還需要使用 AddressBook 架構新的 ABAddressBookRequestAccessWithCompletion 方法,用以獲知使用者是否授權 :
+ (void)fetchContacts:(void (^)(NSArray *contacts))successfailure:(void (^)(NSError *error))failure {
#ifdef __IPHONE_6_0
if (ABAddressBookRequestAccessWithCompletion) {
CFErrorRef err;
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, &err);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
// ABAddressBook doesn‘tgaurantee execution of this block on main thread, but we want our callbacks tobe
dispatch_async(dispatch_get_main_queue(), ^{
if (!granted) {
failure((__bridge NSError *)error);
} else {
readAddressBookContacts(addressBook, success);
}
CFRelease(addressBook);
});
});
}
#else
// on iOS < 6
ABAddressBookRef addressBook = ABAddressBookCreate();
readAddressBookContacts(addressBook, success);
CFRelease(addressBook);
}
#endif
}
這個方法有兩個塊參數 success 和 failure,分別用於執行使用者授權訪問的兩種情況:同意和不同意。
在代碼調用 ABAddressBookRequestAccessWithCompletion函數時,第2個參數是一個塊,該塊的 granted 參數用於告知使用者是否同意。如果 granted 為No(不同意),我們調用failure塊。 如果 granted 為Yes(同意),我們將調用 readAddressBookContacts 函數,進一步讀取連絡人資訊。
readAddressBookContacts 聲明如下:
static voidreadAddressBookContacts(ABAddressBookRef addressBook, void (^completion)(NSArray *contacts)) {
// do stuff with addressBook
NSArray *contacts = (NSArray *)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook));
completion(contacts);
}
首先從 addressBook 中擷取所有連絡人(結果放到一個NSArray 數組中),然後調用 completion 塊(即 fetchContacts 方法的 success 塊)。在 completion 中我們可以對數組進行迭代。
一個調用 fetchContacts 方法的例子:
+(void)getAddressBook:(void(^)(NSArray*))completion{
[self fetchContacts:^(NSArray *contacts) {
NSArray *sortedArray=[contactssortedArrayUsingComparator:^(id a, id b) {
NSString* fullName1=(NSString*)CFBridgingRelease(ABRecordCopyCompositeName((__bridge ABRecordRef)(a)));
NSString* fullName2=(NSString*)CFBridgingRelease(ABRecordCopyCompositeName((__bridge ABRecordRef)(b)));
int len = [fullName1 length] > [fullName2 length]? [fullName2 length]:[fullName1 length];
NSLocale *local = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_hans"];
return [fullName1 compare:fullName2 options:NSCaseInsensitiveSearch range:NSMakeRange(0, len) locale:local];
}];
completion(sortedArray);
} failure:^(NSError *error) {
DLog(@"%@",error);
}];
}
即在 fetchContacts 的完成塊中對連絡人姓名進行中文排序。最後調用 completion 塊。在 fetchContacts 的錯誤塊中,簡單列印錯誤資訊。
調用 getAddressBook的範例程式碼如下:
[AddressBookHelper getAddressBook:^(NSArray *node) {
NSLog(@"%@",NSArray);
}];
86、ARC警告:PerformSelector may cause a leak because itsselector is unknown
這個是 ARC 下特有的警告,用#pragma clang diagnostic宏簡單地忽略它即可:
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Warc-performSelector-leaks"
[targetperformSelector:sel withObject:[NSNumber numberWithBool:YES]];
#pragma clang diagnostic pop
87、‘libxml/HTMLparser.h‘ file not found
匯入 libxml2.dylib 後出現此錯誤,尤其是使用 ASIHTTP 架構的時候。在 Build Settings的 Header SearchPaths 列表中增加“${SDK_DIR}/usr/include/libxml2”一項可解決此問題。
所謂 "$(SDK_ROOT)"是指編譯目標所使用的 SDK 的目錄,以 iPhone SDK 7.0 (真機)為例,是指/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS7.0.sdk目錄。
注意,似乎 Xcode 4.6 以後“User Header Search Paths”(或者“Always Search User Paths”)不再有效,因此在 “User HeaderSearch Paths”中配置路徑往往是無用的,最好是配置在“Header SearchPaths”中。
88、錯誤:-[UITableViewdequeueReusableCellWithIdentifier:forIndexPath:]: unrecognized selector
這是 SDK 6 以後的方法,在 iOS 5.0 中這個方法為:
[UITableViewdequeueReusableCellWithIdentifier:]
89、@YES 文法在 iOS5 中無效,提示錯誤:Unexpected typename ‘BOOL‘: expected expression
在 IOS6 中,@YES定義為:
#define YES ((BOOL)1)
但在 iOS 5 中,@YES 被少寫了一個括弧:
#define YES (BOOL)1
因此 @YES 在 iOS 5 中的正確寫法應當為 @(YES)。為了簡便,你也可以在 .pch 檔案中修正這個 Bug:
#if __has_feature(objc_bool)
#undef YES
#undef NO
#define YES __objc_yes
#define NO __objc_no
#endif
iOS 開發百問(7)