how do i check if an item exists and if it does replace it in NSMutableArray i just cant figure it out all i have so far is:
int i = [arrayOne indexOfObject:#"object to replace"];
NSLog(#"%#", i);
[arrayOne replaceObjectAtIndex:i withObject:#"replace"];
but i keep getting errors :S can anyone help me ?
My array is:
#[ "13L6-A67-1", "13NAPUSD-A1", "13NASUWO-X1", "13NASUWO-X1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASECON-D1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASMATH-C1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13ASPHYS-B1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1", "13B3ITCE-F1" ]
if object is not present in array NSNotFound value is returned, so you need to check for it:
if (i != NSNotFound)
[arrayOne replaceObjectAtIndex:i withObject:#"replace"];
Note also that if you want to print integer value, you should use %d format specifier, %# is used for objective-c objects
It seems you are new to this platform. So here is the sample code that works -
NSMutableArray *arrayOne = [#[#"13L6-A67-1",#"13NAPUSD-A1",#"13NASUWO-X1",#"13NASUWO-X1",#"13ASECON-D1",#"13ASECON-D1",#"13ASECON-D1",#"13ASECON-D1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASMATH-C1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13ASPHYS-B1",#"13B3ITCE-F1",#"13B3ITCE-F1",#"13B3ITCE-F1",#"13B3ITCE-F1" ] mutableCopy];
NSUInteger index = [arrayOne indexOfObject:#"13ASECON-D1"];
if (index != NSNotFound) {
[arrayOne replaceObjectAtIndex:index withObject:#"DIFFERENT_VALUE"];
NSLog(#"arrayOne after replaceObjectAtIndex = %#", arrayOne);
}
General guidelines -
watch out for compiler warning when you build.
put breakpoint and step through your code which doesn't work.
Related
Please suggestion only for NSArray.
NSArray *addressAry = [[arr1 valueForKey:#"var_offline_address"] componentsSeparatedByString:#"$#$"];
for (int i = 0; i<=addressAry.count; i++) {
NSString *str = [addressAry objectAtIndex:i];
if (str containsString:#"NA") {
NSString *strChange;
strChange = #"Address Not Available";
[myMutableArray insertObject:myObject atIndex:42];
To add an object to the front of the array, use 0 as the index:
[myMutableArray insertObject:myObject atIndex:0];
Use NSMutableArray. It has a method called:
- (void)insertObject:(ObjectType)anObject atIndex:(NSUInteger)index
Like:
[yourMutableArray insertObject: theObject atIndex: theIndex];
As it describes:
If index is already occupied, the objects at index and beyond are shifted by adding 1 to their indices to make room.
For more info see the official doc.
I am using iTunes Search APIs to return the number of users that have reviewed my current app version. Since I haven't released the app yet, I have to handle the case where the iT search API returns nothing.
Here's the pertinent code:
NSDictionary *iTunesDict = [NSJSONSerialization
JSONObjectWithData:iTunesData options:0 error:&error];
NSArray *resultCount = #[[iTunesDict valueForKey:#"resultCount"]];
NSLog(#"%#", [resultCount objectAtIndex:0]);
if ([resultCount objectAtIndex:0] == 0) {
self.numberOfReviewers = #"0";
} else {
NSArray *reviewers = #[[[iTunesDict valueForKey:#"results"] valueForKey:#"userRatingCountForCurrentVersion"]];
if ([reviewers objectAtIndex:0] == nil) {
self.numberOfReviewers = #"0";
} else {
NSString *howManyReviewed = [[[reviewers objectAtIndex:0] objectAtIndex:0] stringValue];
self.numberOfReviewers = howManyReviewed;
}
My problem centers around the first if statement. Upon inspection, the value of...
[resultCount objectAtIndex:0] is: (__NSCFNumber *)(long)0
does not satisfy the condition in my first if.
What do I need to make a **(__NSCFNumber *)(long)0 **== 0??
It's returning the data as an NSNumber object. Use the compare: comparison function:
if ([resultCount[0] compare:#0] == NSOrderedSame) {
...
}
else {
...
}
What this is doing is comparing the resultCount object to an NSNumber with the value of 0 (you can use the literal #0 to short-hand an NSNumber as I've done above). compare: returns one of three values:
NSOrderedDescending
NSOrderedSame
NSOrderedAscending
This reads from left to right. So if I was to use NSOrderedDescending, this would read logically "is 0 smaller than resultCount" (in descending order from left to right).
For further reading, check out the comparing NSNumber objects documentation.
Alternatively, because you know it's a long, you can use the longValue method on NSNumber:
if ([resultCount longValue] == 0) {
....
}
I am trying to get the last NSString from a NSMutableArray, and delete it if it's empty.
Here is the code I am using:
- (void)viewWillAppear:(BOOL)animated {
if ([notes.data length]==0){
[storedText removeLastObject];
}
[self.tableView reloadData];
}
data is the NSString and storedText is the NSMutableArray. This code deletes the NSString even if it's not empty. I want it to keep the string if it contains text.
You should try something like this:
- (void)viewWillAppear:(BOOL)animated {
if ([[[storedText lastObject] data] length]==0){
[storedText removeLastObject];
}
[self.tableView reloadData];
}
BTW, it seems that your hypothesis that notes.data is the same string as the last object in storedText is not correct. This leads me to suspect that you have other kinds of errors in your code that you should also investigate. In other words, what you can expect is that your notes.data is not correct -- indeed, you should at least "update" it after you remove the last object from the array:
- (void)viewWillAppear:(BOOL)animated {
if ([[[storedText lastObject] data] length]==0){
[storedText removeLastObject];
notes = [storedText lastObject]; //-- this will be the *new* last object after removal
}
[self.tableView reloadData];
}
but I have no clue what you do with notes.data, so I do not know if this by itself is enough to bring it back to being consistent with your hypothesis.
Ideally before you add any item to storedText you would check that it wasn't nil or an empty string, then you wouldn't have the problem.
Otherwise, get the last item from storedText and check it (using isEqualToString: or a length check) and then remove it if it matches.
Follow what Wain said. Do this.
//total array size
int count = [storedText count];
int lastItemIndexInt = count - 1;
//get last object in array which is a string
NSString *str1 = [storedText objectAtIndex:lastItemIndexInt];
if ([str1 isEqualToString:#""] || [str1 length] < 1)
{
//string is null / blank, remove it
[storedText removeObjectAtIndex:lastItemIndexInt];
}
I have the following code to search the following dictionary:
//NSString *knownObject = #"3:40 am";
NSArray *temp = [itemDict allKeysForObject:knownObject];
NSString *key = [temp objectAtIndex:0];
NSLog(#"prayer: %#", key);
Dict:
{
asr = "4:23 pm";
dhuhr = "12:02 pm";
fajr = "1:16 am";
isha = "10:47 pm";
maghrib = "8:24 pm";
shurooq = "3:40 am";
}
When running the first line, it correctly returns "shurooq". However, when I use my variable:
NSArray *temp = [itemDict allKeysForObject:nextPrayerTime];
The log output of nextPrayerTime is simply 3:40 am as expected.
Why is this not working?
Many thanks!
Checkout the value of nextPrayerTime, if itemDict contain any object same as nextPrayerTime then [itemDict allKeysForObject:nextPrayerTime]; will return an array of keys otherwise it will return empty array.
In your current case anyhow you get an empty array but when you try to access [temp objectAtIndex:0] then compiler couldn't find any object and it gets an array out of bound exception and this cause the crash of your app....
To overcome this exception you should check the count of objects in array...
NSArray *temp = [itemDict allKeysForObject: nextPrayerTime];
if([temp count] > 0) {
NSString *key = [temp objectAtIndex:0];
NSLog(#"prayer: %#", key);
} else
NSLog(#"NO Object Found");
What is the value of nextPrayerTime?
According to the docs, allKeysForObject: returns
A new array containing the keys corresponding to all occurrences of anObject in the dictionary. If no object matching anObject is found, returns an empty array.
Based on the information given I would guess you are getting back an empty array and when you call [temp objectAtIndex:0] you are accessing an index that does not exist and getting an out of bounds exception.
I am not a 100% sure of my answer, but is the method isEqualToString used for comparison of the objects when the object is a NSString?
Otherwise you probably need to compare to the original object in the dictionary (using the same NSString).
This question already has answers here:
How might I check if a particular NSString is present in an NSArray?
(3 answers)
Closed 9 years ago.
I want search (to check) one NSString in NSMutableArray. but I dont know about it.
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
I want to see is there name variable in a NSMutableArray variable ?
Use containsObject: method to check this :
NSMutableArray *a = [[NSMutableArray alloc]initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
if ([a containsObject:name]) {
// Your array cotains that object
}
Hope it helps you.
run a loop and check .
-(BOOL)array:(NSArray*)array containsString:(NSString*)name
{
for(NSString *str in array)
{
if([name isEqualToString:str])
return YES;
}
return NO;
}
In this way array find out object that it contains.
you can also use a single line
[array containsObject:name]
If you are also interested in the position of your element you can use
- (NSUInteger)indexOfObject:(id)anObject
it will return NSNotFound if the object is not in the array, or the index of the object
You can use the following code
if([a containsObject: name])
{
//here your code
}
[a containsObject:name]
This might help you.
I suggest you to use indexOfObject:. Because using this way you can not only check whether it exists but also get the index if it indeed exists.
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects:#"Marco",#"christian",#"hon",#"John",#"fred",#"asdas", nil];
NSString *name = #"John";
NSInteger index = [array indexOfObject:name];
if (index != NSNotFound) {
NSLog(#"Find name %#", name);
} else {
NSLog(#"Name %# not fount", name);
}