IOS array out-of-bounds crash processing experience

Source: Internet
Author: User

Let's take a look at the possible array of crash where arrays are out of bounds;

-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath {    Welfareitem *item = [_datasourcearray objectatindex:indexpath.row];//may be out of bounds, you will use [_datasourcearray removeallobjects] when the pull-down is refreshed. Then you order a cell and you will crash}-(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {    Welfareitem *item = _datasourcearray[indexpath.row];//may be out of bounds, two places used [TableView reloaddata]; the latter one has [_ Datasourcearray Removeallobjects]; the previous one has not finished, it will crash}


The above code is likely to cross the line, the occurrence of crash is not good to reproduce, sent to the app always receive a few crash; the solution to this problem is also simple code as follows:

-(void) TableView: (UITableView *) TableView Didselectrowatindexpath: (Nsindexpath *) Indexpath {    Welfareitem *item = Nil;    if (Indexpath.row < [_datasourcearray count]) {//No matter how high your kung fu is, sometimes you will forget to add        item = [_datasourcearray Objectatindex: Indexpath.row];}    } -(UITableViewCell *) TableView: (UITableView *) TableView Cellforrowatindexpath: (Nsindexpath *) Indexpath {    Welfareitem *item = nil;    if (Indexpath.row < [_datasourcearray count]) {        item = [_datasourcearray ObjectAtIndex:indexPath.row];    }}


The problem comes again, no matter how high your martial arts, sometimes forget to add; so we have to think of a way of making enemies; I thought of using runtime to replace the Objectatindex method; The code is as follows:

/*! @category @abstract nsobject category */@interface NSObject (Util)/*! @method swizzlemethod:withmethod:error:@ Abstract replace the instance method with @param oldselector the method that you want to replace @param newselector the actual replacement with the method @param the error that occurs during the replace error, if there is a nil*/+ (BOOL) Swizzlemethod: (SEL) originalselector Withmethod: (SEL) Swizzledselector error: (NSERROR *) error; @end #import "NSObject +util.h "#import @implementation nsobject (Util) + (BOOL) Swizzlemethod: (SEL) originalselector Withmethod: (SEL)    Swizzledselector Error: (Nserror *) error{Method Originalmethod = Class_getinstancemethod (self, originalselector); if (!originalmethod) {nsstring *string = [NSString stringwithformat:@ '%@ class did not find%@ method ', Nsstringfromclass ([self CLA SS]), Nsstringfromselector (originalselector)];*error = [Nserror errorwithdomain:@ "Nscocoaerrordomain" code:-1        Userinfo:[nsdictionary dictionarywithobject:string Forkey:nslocalizeddescriptionkey]];    return NO;    } Method Swizzledmethod = Class_getinstancemethod (self, swizzledselector); if (!Swizzledmethod) {NSString *string = [NSString stringwithformat:@ "%@ class not found%@ method", Nsstringfromclass ([Self class]), Nsstringfromselector (swizzledselector)];*error = [Nserror errorwithdomain:@ "Nscocoaerrordomain" Code:-1 userInfo:[        Nsdictionary dictionarywithobject:string Forkey:nslocalizeddescriptionkey]];    return NO; } if (Class_addmethod (self, originalselector, method_getimplementation (Swizzledmethod), method_gettypeencoding (SWiZ Zledmethod)) {Class_replacemethod (self, swizzledselector, method_getimplementation (Originalmethod), METHOD_GETTYP    Eencoding (Originalmethod));    } else {method_exchangeimplementations (Originalmethod, Swizzledmethod); } return YES;    @end @implementation Nsarray (errermanager) + (void) load{static dispatch_once_t Oncetoken; Dispatch_once (&oncetoken, ^{@autoreleasepool {[Objc_getclass ("__nsarrayi") swizzlemethod:@s Elector (Objectatindex:) Withmethod: @selector (swizzleobjectatindex:) Error:nil]; [Objc_getclass ("__nsarraym") Swizzlemethod: @selector (objectatindex:) Withmethod: @selector (swizzleobjectatindex:)        Error:nil];    }; });} -(ID) Swizzleobjectatindex: (Nsuinteger) index{if (Index < self.count) {return [self Swizzleobjectatindex:    Index];    } NSLog (@ "%@ out of Bounds", self); Return nil;//out of bounds returns to nil} @end


With the above code we use [_datasourcearray ObjectAtIndex:indexPath.row] will not occur in the cross-border crash;
will return nil; it seems to be a better solution; send out the app, and we crash several times higher than before (crash out of bounds, out of the new crash); crash as follows

1 tbreader 0x002b93e9 Tbreader + 20981532 libsystem_platform.dylib 0x33a66873 _sigtramp + 343 Libsystem_blocks.dylib 0x339 41AE1 _block_release + 2164 LIBOBJC. A.dylib 0x333c11a9 + 4045 corefoundation 0x25ba23a9 _cfautoreleasepoolpop + 166 UIKit 0x2912317f + 427 CoreFoundation 0x25 C565CD + 208 corefoundation 0x25c53c8b + 2789 corefoundation 0x25c54093 + 91410 corefoundation 0x25ba2621 CFRunLoopRunSpec ific + 47611 corefoundation 0x25ba2433 cfrunloopruninmode + 10612 graphicsservices 0x2cf0a0a9 GSEventRunModal + 13613 UIKi T 0x2918c809 Uiapplicationmain + 1440

Are this crash, appear in iOS7 above (including iOS7), the key has no user feedback has a problem, crash high several times no user feedback This situation is still rare, we can not reproduce the test; The test has finally reproduced the same crash; Replaced the Objectatindex method has the input of the place out of the soft keyboard press the home button on the phone crash; This method is not only, but also to find his strategy. Then we'll add the extension method code to the array as follows

@interface Nsarray (shyutil)/*! @method Objectatindexcheck: @abstract Check if it is out of bounds and nsnull if it returns nil @result return object */-(ID) Objectatindexcheck: (nsuinteger) index ; @end #import "Nsarray+shyutil.h" @implementation Nsarray (Shyutil)-(ID) Objectatindexcheck: (Nsuinteger) index{    if (index >= [self count]) {        return nil;    }        ID value = [self objectatindex:index];    if (value = = [NSNull null]) {        return nil;    }    return value;} @end

Change the previous code welfareitem *item = [_datasourcearray ObjectAtIndex:indexPath.row] to Welfareitem *item = [_datasourcearray Object AtIndexCheck:indexPath.row] It's OK. This allows the array to be completely out of bounds-[__nsarrayi Objectatindex:]: Index beyond bounds [0.. 1] ' wrong

IOS array out-of-bounds crash processing experience

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.