71. How to make the size of UIWebView conform to the HTML content?
In iOS5, this is very simple, set the webview delegate, and then implement didFinishLoad: method in the delegate:
-(void)webViewDidFinishLoad:(UIWebView*)webView{ CGSizesize=webView.scrollView.contentSize;//iOS5+ webView.bounds=CGRectMake(0,0,size.width,size.height); }
72. There are multiple Responders in the window, how to quickly release the keyboard
[[UIApplicationsharedApplication]sendAction:@selector(resignFirstResponder)to:nilfrom:nilforEvent:nil];
In this way, all Responders can lose focus at once.
73. How to enable UIWebView to zoom through the "pinch" gesture?
Use the following code:
webview=[[UIWebViewalloc]init]; webview.autoresizingMask=(UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight); webview.scalesPageToFit=YES; webview.multipleTouchEnabled=YES; webview.userInteractionEnabled=YES;
74, Undefinedsymbols:_kCGImageSourceShouldCache, _CGImageSourceCreateWithData, _CGImageSourceCreateImageAtIndex
ImageIO.framework is not imported.
75, expectedmethodtoreaddictionaryelementnotfoundonobjectoftypensdictionary
SDK6.0 has added a "subscript" index to the dictionary, that is, retrieving objects in the dictionary through dictionary[@"key"]. But in SDK5.0, this is illegal. You can create a new header file NSObject+subscripts.h in the project to solve this problem. The content is as follows:
#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, error: -[MKNetworkEnginefreezeOperations]:messagesenttodeallocatedinstance0x1efd4750
This is A memory management error. The MKNetwork framework supports ARC, and memory management problems should not occur. However, due to some bugs in MKNetwork, this problem occurs when MKNetworkEngine is not set to the strong attribute. It is recommended that the MKNetworkEngine object be set to the strong attribute of ViewController.
77. The difference between UIImagePickerControllerSourceTypeSavedPhotosAlbum and UIImagePickerControllerSourceTypePhotoLibrary
UIImagePickerControllerSourceTypePhotoLibrary represents the entire photo library, allowing users to select all photo albums (including camera roll), while UIImagePickerControllerSourceTypeSavedPhotosAlbum only includes camera roll.
78. Warning "Prototypetablecellsmusthaveresueidentifiers"
The Identidfier attribute of Prototypecell (iOS5 template cell) is not filled in, just fill it in the attribute template.
79. How to read the value in info.plist?
The following example code reads the URLSchemes in info.plist:
//TheInfo.plistisconsideredthemainBundle. mainBundle=[NSBundlemainBundle]; NSArray*types=[mainBundleobjectForInfoDictionaryKey:@"CFBundleURLTypes"]; NSDictionary*dictionary=[typesobjectAtIndex:0]; NSArray*schemes=[dictionaryobjectForKey:@"CFBundleURLSchemes"]; NSLog(@"%@",[schemesobjectAtIndex:0]);
80. How to prevent ActionSheet from automatically disbanding?
UIActionSheet will eventually be automatically dismissed no matter what button is clicked. The best way is to subclass it, add a noAutoDismiss attribute and override the dismissWithClickedButtonIndex method. When this attribute is YES, no dismissal action is performed. When it is NO, the default dismissWithClickedButtonIndex is called:
#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 ,Crash when executing RSA_public_encrypt function
This problem is very strange. Using two devices, one with system 6.1 and one with 6.02, the same code works fine in version 6.02, but causes the program to crash in version 6.1:
unsignedcharbuff[2560]={0}; intbuffSize=0; buffSize=RSA_public_encrypt(strlen(cleartext), (unsignedchar*)cleartext,buff,rsa,padding);
The problem lies in this sentence:
buffSize=RSA_public_encrypt(strlen(cleartext), (unsignedchar*)cleartext,buff,rsa,padding);
6.1 System iPad is a 3G version. Due to the unstable signal of the 3G network (China Unicom 3gnet) used, the rsa public key cannot be obtained frequently, so the rsa parameter appears nil. The 6.0 system iPad is a wifi version and the signal is stable, so there is no such problem. The solution is to check the validity of the rsa parameters.
82. Warning: UITextAlignmentCenterisdeprecatediniOS6
NSTextAlignmentCenter has been replaced by UITextAlignmentCenter. There are some similar alternatives. You can use the following macro:
#ifdef__IPHONE_6_0//iOS6andlater #defineUITextAlignmentCenter(UITextAlignment)NSTextAlignmentCenter #defineUITextAlignmentLeft(UITextAlignment)NSTextAlignmentLeft #defineUITextAlignmentRight(UITextAlignment)NSTextAlignmentRight #defineUILineBreakModeTailTruncation(UILineBreakMode)NSLineBreakByTruncatingTail #defineUILineBreakModeMiddleTruncation(UILineBreakMode)NSLineBreakByTruncatingMiddle #endif
83. -fno-objc-arc cannot be set in Xcode5
Xcode5 uses ARC by default and hides the " CompilerFlags" column, so you cannot set the -fno-objc-arc option of the .m file. To display the CompilerFlags column of the .m file, you can use the menu "View->Utilities->HideUtilities" to temporarily close the Utilities window on the right to display the CompilerFlags column, so that you can set the -fno- of the .m file. objc-arc flag.
84. Warning: 'ABAddressBookCreate'isdeprecated: firstdeprecatediniOS6.0
This method will be abandoned after iOS6.0 and replaced by the ABAddressBookCreateWithOptions method:
CFErrorRef*error=nil; ABAddressBookRefaddressBook=ABAddressBookCreateWithOptions(NULL,error);
85. How to read after iOS6.0 Get your cell phone address book?
After iOS6, the AddressBook framework has changed, especially that the app needs to obtain user authorization to access the mobile address book. Therefore, in addition to using the new ABAddressBookCreateWithOptions initialization method, we also need to use the new ABAddressBookRequestAccessWithCompletion method of the AddressBook framework to know whether the user is authorized:
+(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 }
This method has two block parameters success and failure, respectively used to perform two situations of user authorized access: consent and disagreement.
When the code calls the ABAddressBookRequestAccessWithCompletion function, the second parameter is a block, and the granted parameter of the block is used to inform the user whether to agree. If granted is No (disagree), we call the failure block. If granted is Yes (agree), we will call the readAddressBookContacts function to further read the contact information.
readAddressBookContacts is declared as follows:
staticvoidreadAddressBookContacts(ABAddressBookRefaddressBook,void(^completion)(NSArray*contacts)){ //dostuffwithaddressBook NSArray*contacts=(NSArray*)CFBridgingRelease(ABAddressBookCopyArrayOfAllPeople(addressBook)); completion(contacts); }
First get all contacts from addressBook (the results are placed in an NSArray array), and then call the completion block (that is, the success block of the fetchContacts method). In completion we can iterate over the array.
An example of calling the fetchContacts method:
+(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)!