Runtime immutable groups __nsarray0 and __nsarrayi in IOS
You may have all encountered an immutable group in a project to avoid the processing of arrays out of bounds: runtime, however, sometimes it does not solve all the problems, because the cluster is not the same
#import "Nsarray+security.h"
#import "Nsobject+swizzling.h"
@implementation Nsarray (Security)
+ (void) Load {
Static dispatch_once_t Oncetoken;
Dispatch_once (&oncetoken, ^{
[Objc_getclass ("__nsarray0") Methodswizzlingwithoriginalselector: @selector (objectatindex:) byswizzledselector:@ Selector (safeobjectatindex:)];
});
}
-(ID) Safeobjectatindex: (Nsuinteger) Index {
if (Self.count = = 0) {
NSLog (@ "%s can ' t get any object from an empty array", __function__);
return nil;
}
if (Index > Self.count) {
NSLog (@ "%s index out of bounds in array", __function__);
return nil;
}
return [self safeobjectatindex:index];
}
@end
But different ways of creating arrays result in different classes of clusters (which are actually different pointers), so let's look at
Nsarray *arr1 = @[@ "1", @ "2"];
Nsarray *ARR2 = [[Nsarray alloc]init];
Nsarray *ARR2 = [[Nsarray alloc]initwithobjocts:@ "1", nil];
Nsarray *ARR3 = [Nsarray alloc];
Nsmutblearray *ARR4 = [Nsmutblearray array];
You will find:
1, ARR2 class called _nsarray0
2, not init ARR3, the class name is called _nsplaceholderarray;
3, the variable array class name after initialization is called _nsarraym;
4, after the initialization of the immutable group class name is called _nsarrayi.
So be careful when doing runtime processing!
Runtime immutable groups __nsarray0 and __nsarrayi in IOS