NSRange changes itself inside for loop - ios

I have an NSDictionary of NSRange objects, with keys for their index in the array. I am attempting to use each of these ranges to create substrings of a larger string, and place each of these substrings in the array. I basically have this completed, but the NSRange is mysteriously changing it's value in the code, causing it to crash and throw an exception. Here is my code:
NSMutableArray*subStringArray = [[NSMutableArray alloc] init];
for(id key in aDict){
NSRange* range = CFBridgingRetain([aDict objectForKey:key]);
NSLog(#"This is a single range: %#",range);
//Range is changed here somehow
NSString* aSubString = [self.content substringWithRange:*range];
NSLog(#"%#",aSubString);
[subStringArray addObject:aSubString];
}
My Log output looks like this:
This is a single range: NSRange: {1874, 72}
2014-06-17 20:07:30.100 testApp[8027:60b] *** Terminating app due to uncaught exception
'NSRangeException', reason: '-[__NSCFString substringWithRange:]: Range {4318599072, 4} out of bounds; string length 5562'

By popular demand :)
The main issue with your code is that you are directly storing an NSRange struct in your dictionary. You can't do this. You must wrap the NSRange in an NSValue to store it in the dictionary.
To add the NSRange you can do:
NSRange range = ... // some range
NSValue *value = [NSValue valueWithRange:range];
dict[someKey] = value;
Then your posted code becomes:
for (id key in aDict) {
NSValue *value = aDict[key];
NSRange range = [value rangeValue];
NSLog(#"This is a single range: %#",range);
//Range is changed here somehow
NSString* aSubString = [self.content substringWithRange:range];
NSLog(#"%#",aSubString);
[subStringArray addObject:aSubString];
}

Related

How to get a NSRange Value from NSConcreteValue?

The code is like this. My question is how to get the NSRange value from the id type?
-(void)clicText:(MyLabel *)label clickedOnLink:(id)linkData{
NSString *message = [NSString stringWithFormat:#"LinkData is %#:%#",[[linkData class] description],linkData];
}
I get the type is NSConcreteValue and the data value is NSRange:{0,4}; but how do I get the NSRange from the NSConcreteValue?
I have already tried the [NSValue valueWithNonretainedObject:linkData]; but it does not make sense.
Use the rangeValue method:
NSRange range = [linkData rangeValue]; // assume linkData is NSValue

-[__NSArrayI length]: crash when trying to filter with searchController [duplicate]

This question already has answers here:
How can I debug 'unrecognized selector sent to instance' error
(9 answers)
Closed 8 years ago.
I'm trying to filter with searchController. I am getting a crash (-[__NSArrayI length]: unrecognized selector sent to instance) at line NSRange productNameRange = NSMakeRange(0, [[_list valueForKey:#"name"] length]); in the following code:
-(void)updateFilteredContent:(NSString*)searchText {
// Update the filtered array based on the search text and scope.
[self.searchResults removeAllObjects];
// Filter the array using NSPredicate
NSLog(#"_categories are %#",_categories);
for (NSDictionary *object in _categories) {
NSUInteger searchOptions = NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch;
NSRange productNameRange = NSMakeRange(0, [[_list valueForKey:#"name"] length]);
NSRange foundRange = [[_list valueForKey:#"name"] rangeOfString:searchText options:searchOptions range:productNameRange];
if (foundRange.length > 0) {
[self.searchResults addObject:object];
}
}
}
I've tried adding an if statement on the length like if ([[object valueForKey:#"name"] length] >0){ but it still crashing.
an example of the log for _list is:
_list names are (
"Honda",
"Ford",
Toyota,
your [_list valueForKey:#"name"] returns an NSarray, which should be an NSString to calculate length of it..
Please check with this condition and let me know if it still crashes!
if([_list allkeys] contains #"name"])
{
NSString *tempStr = [_list valueForKey:#"name"];
}
if(tempStr)
NSRange productNameRange = NSMakeRange(0, [tempStr length]);

Terminating app due to uncaught exception 'NSRangeException', reason

I am using search bar in collection,when I am doing filter text I got the error like
` Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 2147483647 beyond bounds [0 .. 37]'
*** First throw call stack:
`
Here is my code
- (void)filterListForSearchText:(NSString *)searchText
{
for (NSString *title in _arrayCCName) {
NSRange nameRange = [title rangeOfString:searchText options:NSCaseInsensitiveSearch];
if (nameRange.location != NSNotFound) {
[_searchResultName addObject:title];
}
}
for (int i=0; i<_searchResultName.count; i++) {
NSString *str=[ObjCls objectAtIndex:i];
NSInteger index=[_searchResultName indexOfObject:str];
[_searchResultDeignation addObject:[_arrayCCDesignation objectAtIndex:index]];
[_searchResultProfilePicture addObject:[_arrayCCProfilePicture objectAtIndex:index]];
[_searchResultFamilyPicture addObject:[_arrayCCFamilyPicture objectAtIndex:index]];
NSLog(#"array index is %ld",(long)index);
}
}
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
SEARCHBAR.showsCancelButton=NO;
[self.view endEditing:YES];
}
I got above error please help me how it is solve?
Simply means that the value of index is greater than the size of array at some point. When using [array objecAtIndex:index], index must be less than array.count.
These lines here....
NSInteger index=[_searchResultName indexOfObject:str];
[_searchResultDeignation addObject:[_arrayCCDesignation objectAtIndex:index]];
[_searchResultProfilePicture addObject:[_arrayCCProfilePicture objectAtIndex:index]];
[_searchResultFamilyPicture addObject:[_arrayCCFamilyPicture objectAtIndex:index]];
NSLog(#"array index is %ld",(long)index);
You are assuming that the indexOfObject actually finds something. What happens if the str doesn't exist
Taken from the documentation....
Declaration
OBJECTIVE-C
- (NSUInteger)indexOfObject:(id)anObject
Parameters
anObject
An object.
Return Value
The lowest index whose corresponding array value is equal to anObject. If none of the objects in the array is equal to anObject, returns NSNotFound.

ios - get values from NSDictionary

I have JSON on my server, which is parsed into iOS app to NSDictionary. NSDictionary looks like this:
(
{
text = Aaa;
title = 1;
},
{
text = Bbb;
title = 2;
}
)
My question is - how to get just text from first dimension, so it should be "Aaa". I've tried to use this:
[[[json allValues]objectAtIndex:0]objectAtIndex:0];
But it didn't work, it ends with error
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[__NSCFArray allValues]:
unrecognized selector sent to instance 0x714a050'
So can you help me please, how to get just one value from specified index? Thanks!
That error message is simply telling you that NSDictionary (which is the first object of that array, along with the second) doesn't respond to objectAtIndex.
This will be a bit cody, but it explains it better:
NSArray *jsonArray = [json allValues];
NSDictionary *firstObjectDict = [jsonArray objectAtIndex:0];
NSString *myValue = [firstObjectDict valueForKey:#"text"];
Your JSON object is an array, containing two dictionaries. That's how to get the values:
NSDictionary* dict1= json[0];
NSString* text= dict1[#"text"];
NSString* title= dict1[#"title"];
Try this:
NSString *txt = [[json objectAtIndex:0] objectForKey:#"text"];
UPDATE: Have fixed the error. Thanks yunas.

How to fix this mutating error?

I'm getting this error:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceCharactersInRange:withString:'
But I can't figure out what immutable object I'm mutating.
NSRange subRange = [self.label.text rangeOfString: #"="];
int numA = 5;
int numB = 3;
NSMutableString *mixed = [NSString stringWithFormat: #"%i %i", numA, numB];
NSMutableString *string = [NSString stringWithString: self.label.text];
subRange = [string rangeOfString: #"="];
if (subRange.location != NSNotFound)
[string replaceCharactersInRange:subRange withString:mixed];
Your NSMutableString creation calls aren't balanced properly. You're promising the compiler that you're creating a NSMutableString but you ask an NSString to create an instance.
For example:
NSMutableString *mixed = [NSString stringWithFormat: #"%i %i", numA, numB];
needs to be:
NSMutableString *mixed = [NSMutableString stringWithFormat: #"%i %i", numA, numB];
Your NSMutableStrings are actually instances of NSString. This is runtime detail, though there should at least be a warning for those lines. Change to:
NSMutableString *string = [self.label.text mutableCopy];
You need to create a NSMutableString like this:
[NSMutableString stringWithString: self.label.text];

Resources