Klaus Klaus - 1 year ago 92
Objective-C Question

obj-c cannot find index from searched array / wrong output

Whatever I do in whatever combination,

always returns a wrong index-number of the successfully searched array-object.


UIButton *xbutton = (UIButton *)sender;
// NSLog(@"%@arraysucks",);
//NSArray *subviews = [self.coview subviews];

// same bogus oupit of index like in [self.coview subviews] :
NSArray *subviews= [[NSArray alloc] initWithObjects:xbutton,nil];
NSString *search = [NSString stringWithFormat:@"tag = %ld%@", [sendertag],@";"];
// test search .
NSString *dummysearch= @"tag = 54;";
NSLog(@"%@%@",@" : search", search);
NSLog(@"%@%@",@" : search",dummysearch);
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subviews CONTAINS %@",search];
NSLog(@"%@predicate", predicate);
NSArray *filteredArray = [subviews filteredArrayUsingPredicate:predicate];
NSString *findtag = [NSString stringWithFormat:@"%@", predicate];

NSString *gettag = [findtag substringFromIndex: 24];
NSString *lastget = [gettag substringToIndex:NSMaxRange([gettag rangeOfComposedCharacterSequenceAtIndex:2])];
long value = [lastget longLongValue];
NSLog(@"findtag: %@", gettag);
NSLog(@"lastget: %@", lastget);


if([sender tag]!= value){
[[subviews objectAtIndex:value] setTitle:_resetbuttonTitle forState:UIControlStateNormal];
xbutton.backgroundColor = [UIColor whiteColor];

NSLog(@"%ldsendertag",[sender tag]);
NSInteger anIndex=[filteredArray indexOfObject:xbutton];
NSLog(@"%ld : isIndex",anIndex);

NSLog output:

UIButton: 0x7fdf1a422550; frame = (161 281; 42 42); opaque = NO; tag = 48; layer = <CALayer: 0x600000224ee0>>
: searchtag = 48;
: searchtag = 54;
subviews CONTAINS "tag = 48;"predicate
findtag: 48;"
lastget: 48
9223372036854775807 : isIndex

Except the bogus index-output all array-search is successful, but what I really need is the index.

Answer Source

You seems to be trying to use NSPredicate to find a view inside the array with its tag. In that case you're doing it incorrectly. You should do that instead:

NSString *search = [NSString stringWithFormat:@"self.tag = %ld", [sender tag]];
NSPredicate * predicate = [NSPredicate predicateWithFormat:search];
NSArray *filteredArray = [subviews filteredArrayUsingPredicate:predicate];

Reference: iOS: How to filter a NSArray of subviews by tag using NSPredicate

Also, 9223372036854775807 is 0x7FFFFFFFFFFFFFFF in hexadecimal, which is the unsigned representation of -1 in 64 bit variables, which is the case of NSInteger (long int). When indexOfObject: returns -1, that's because the object isn't in the array.

Basically, filteredArray doesn't contains xbutton since the predicate was done incorrectly. You can confirm that by printing filteredArray with NSLog.