Replacing a specified dictionary in NSMutableArray - objective-c

I'm trying to replace a dictionary in a mutable array.
Steps 1 through 4 should be good, but I'm having some trouble in step 5 - 6. Can you show me what has to be done to make this function work:
- (void) updatePlist {
// 1: String with plist path:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory
stringByAppendingPathComponent:#"Object.plist"];
// 2: Create a mutable dictionary containing current object and write
// "Yes" to the "Favorite" string:
NSMutableDictionary *mutDict = [NSMutableDictionary
dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:#"Yes" forKey:#"Favorite"];
// 3: Make a string containing current object name:
NSString *nameString = [[detailsDataSource objectAtIndex:detailIndex]
valueForKey:#"Name"];
// 4: Make a mutable array containing all objects:
NSArray *allObjectsArray = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
// 5: Search for the dictionary in tmpMutArr with "Name" value matching nameString:
int *index;
for(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:[NSString
stringWithFormat:#"%#", nameString]])nameString];)
{
index = i;
}
}
}
// 6: Replace the old dictionary with the new one and write array to plist:
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
allObjectsArray = nil;
allObjectsArray = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjectsArray writeToFile:path atomically:YES];
}
EDIT:
Now the problem is:
for(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([[tempDict valueForKey:#"Name"] isEqualToString:
[NSString stringWithFormat:#"%#", nameString]])nameString];)
{
index = i; // Here 1
}
}
}
// ---------------------------- v And here 2
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
1: Incompatible integer to pointer conversion assigning to 'int' from 'int'; take the adress with &
2: Incompatible pointer to integer conversion sending 'int *' to parameter of type NSUInteger' (aka 'unsigned int')

Replace the line:
if([tempDict valueForKey:#"Name" == [NSString stringWithFormat:#"", nameString];)
with this line:
if([[tempDict valueForKey:#"Name"] isEqualToString: [NSString stringWithFormat:#"%#", nameString]])
since you are using string comparison here.

As pointed out in the comments by Martin R, you are trying to save an int value into a int pointer variable.
int index; //instead of 'int *index;'
That change should do the trick.
It could have worked if you had written int *index; and then index = &i;, since you are saving a pointer to an integer that way. But it doesn't seem to be what you are trying to do.
The second error is due you are providing an int pointer instead of an integer to this method:
[tmpMutArr replaceObjectAtIndex:index withObject:
[NSDictionary dictionaryWithDictionary:mutDict]];
But declaring index as an integer solves both errors already.

Related

replace an object inside nsmutablearray

I have a NSMutableArray where i want to replace the sign | into a ; how can i do that?
NSMutableArray *paths = [dic valueForKey:#"PATH"];
NSLog(#"pathArr ", paths)
pathArr (
(
"29858,39812;29858,39812;29925,39804;29936,39803;29949,39802;29961,39801;30146,39782;30173,39779;30220,39774;30222,39774|30215,39775;30173,39779;30146,39782;29961,39801;29949,39802;29936,39803;29925,39804;29858,39812;29858,39812;29856,39812;29800,39819;29668,39843;29650,39847;29613,39855;29613,39855;29613,39856;29605,39857;29603,39867;29603,39867;29599,39892;29596,39909;29587,39957;29571,40018;29563,40038;29560,40043"
)
)
Update
This is where i got my path from
NSArray *BusRoute = alightDesc;
int i;
int count = [BusRoute count];
for (i = 0; i < count; i++)
{
NSLog (#"BusRoute = %#", [BusRoute objectAtIndex: i]);
NSDictionary *dic = [BusRoute objectAtIndex: i];
NSMutableArray *paths = [dic valueForKey:#"PATH"];
}
Provide that your object in the array path is string, you can do this
NSMutableArray *path2=[[NSMutableArray alloc]initWithArray:nil];
for (NSObject *obect in path) {
for (NSString *string in (NSArray*)obect) {
[path2 addObject:[string stringByReplacingOccurrencesOfString:#"|" withString:#","]];
}
}
NSLog(#"pathArr %# ", path2);
your array paths contains an another array which has string as object.
Hope this helps
//Copy the Array into a String
NSString *str = [paths componentsJoinedByString: #""];
//then replace the "|"
str = [str stringByReplacingOccurrencesOfString:#"|" withString:#";"];
i did this to replace a string in a .plist so it might work for you
array1 = [NSMutableArray arrayWithContentsOfFile:Path1];
NSString *item = [#"dfdfDF"];
[array1 replaceObjectAtIndex:1 withObject:item];
[array1 writeToFile:Path1 atomically:YES];
NSLog(#"count: %#", [array1 objectAtIndex:1]);
you may cast or convert paths to NSString and then do:
paths = (NSString *) [paths stringByReplacingOccurrencesOfString:#"|" withString:#";"];
if this does't work, create new NSString instance that containing pathArr text, invoke replaceOccurrences method and do invert conversion
NSMutableString *tempStr = [[NSMutableString alloc] init];
for (int i = 0; i < [paths count]; i++)
{
[tempStr appendString:[path objectAtIndex:i]];
}
then use this method for tempStr. And then try:
NSArray *newPaths = [tempStr componentsSeparatedByString:#";"];
may be last method not completely correct, so try experiment with it.
Uh, why don't you just go:
NSString *cleanedString = [[[dic valueForKey:#"PATH"] objectAtIndex:0] stringByReplacingOccurrencesOfString:#";" withString:#"|"];
If there are more than one nested array, you can go
for(int i = 0; i < [[dic valueForKey:#"PATH"] count]; i++)
{
NSString *cleanedString = [[[dic valueForKey:#"PATH"] objectAtIndex:i] stringByReplacingOccurrencesOfString:#";" withString:#"|"];
// do something with cleanedString
}

Adding objects from array to dictionary

I am getting rows from a SQLite DB and trying to insert them into a dictionary. Except I keep getting errors! I get the error "Implicit conversion of an Objective-C pointer to 'const id *' is disallowed with ARC" Which I know means that I cant use a pointer when I am adding objects to my dictionary. So how do I go about fixing it so I can add those arrays to a dictionary?
NSArray *keyArray = [[NSMutableArray alloc] init ];
NSArray *valueArray = [[NSMutableArray alloc ] init ];
NSDictionary* dic;
NSInteger dataCount = sqlite3_data_count(statement);
while (sqlite3_step(statement) == SQLITE_ROW) {
#try {
for (int i = 0; i < dataCount; i ++)
{
NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
if ([value length] == 0)
{
value = #"";
}
keyArray = [keyArray arrayByAddingObject:key];
valueArray = [valueArray arrayByAddingObject:value];
}
}
#catch (NSException *ex)
{
NSLog(#"%#,%#", [ex name], [ex reason]);
}
dic= [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray count:[keyArray count]];
The dictionaryWithObjects:forKeys:count: takes C-style arrays, not NSArray objects. The dictionaryWithObjects:forKeys: may do the trick, but you may be better off constructing a mutable dictionary as you go, bypassing NSArrays entirely.
NSDictionary* dic;
NSMutableDictionary *tmp = [NSMutableDictionary dictionary];
for (int i = 0; i < dataCount; i ++)
{
NSString* key = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
NSString *value = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, i)];
[tmp setObject:value forKey:key];
}
dict = tmp;
[dicBodyPost setValue:arrContactAddress forKey:#"contactAddress"];

opencv ios cvseq storage

I am intending to pre-load all the images that I have stored inside application. Pre-loading of images involves:
Read images from bundle.
Extract object descriptors using cvExtractSurf from opencv framework.
Store IPLImage with corresponding object descriptors and keypoints.
I am having an issue in creating a dictionary containing CvSeq* keys and CvSeq* descs.
Please suggest how to store these values in NSMutableDictionary.
-(void) preloadImages:(NSMutableDictionary *)dictionary{
NSArray *d = [[NSBundle mainBundle] pathsForResourcesOfType:#"png" inDirectory:nil];
CvSURFParams params = cvSURFParams(500, 1);
CvMemStorage* storage = cvCreateMemStorage(0);
for( int i=0;i<[d count];i++){
NSString *searchForMe = #"myapp.app/1";
NSString *s = [[NSString alloc] initWithString:[d objectAtIndex:i]];
NSRange range = [s rangeOfString:searchForMe];
if( range.location != NSNotFound ){
NSMutableDictionary *surfDict = [[NSMutableDictionary alloc] init];
NSString *substring = [s substringFromIndex:range.location];
substring = [substring stringByReplacingOccurrencesOfString:#"myapp.app/" withString:#""];
UIImage *testImage = [UIImage imageNamed:substring];
IplImage *iplTestImage = [OpenCVUtilities CreateGRAYIplImageFromUIImage:testImage];
CvSeq *keys = 0 ;
CvSeq *descs = 0;
cvExtractSURF( iplTestImage, 0, &keys, &descs, storage, params );
[surfDict setObject:(id)testImage forKey:#"uiImage"];
NSLog(#"Image name : %#", substring);
[dictionary setObject:surfDict forKey:[NSString stringWithFormat:#"%d",i]];
[dictionary setObject:(NSObject *)keys forKey:#"keys"]; // error here
[dictionary setObject:(NSObject *)descs forKey:#"descs"]; // error here
[surfDict release];
}
}
}
Create a class that has an instance variable of type cvseq, add your cvseq to the object, and add that class to the dictionary.

how to remove an NSMutableArray object by key?

i have structured an NSMutableArray and here is an example
(
{
Account = A;
Type = Electricity;
},
{
Account = B;
Type = Water;
},
{
Account = C;
Type = Mobile;
} )
when i try to delete Account B using
[data removeObject:#"B"];
Nothing Happens
[[NSUserDefaults standardUserDefaults] synchronize];
NSArray *archivedArray = [NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
} else {
data = [[NSMutableArray alloc] initWithArray:archivedArray];
}
If you're actually using an array and not a dictionary, you need to search for the item before you can remove it:
NSUInteger index = [data indexOfObjectPassingTest:^BOOL (id obj, NSUInteger idx, BOOL *stop) {
return [[(NSDictionary *)obj objectForKey:#"Account"] isEqualToString:#"B"];
}];
if (index != NSNotFound) {
[data removeObjectAtIndex:index];
}
Alternative: try a NSMutableDictionary:
NSArray *accounts = [NSArray arrayWithObjects:#"A", #"B", #"C", nil];
NSArray *types = [NSArray arrayWithObjects:#"Electricity", #"Water", #"Mobile", nil];
NSMutableDictionary* data = [NSMutableDictionary dictionaryWithObjects:types forKeys:accounts];
[data removeObjectForKey:#"B"];
An NSArray is like a list of pointers, each pointer points to an object.
If you call:
[someArray removeObject:#"B"];
You create a new NSString object that contains the string "B". The address to this object is different from the NSString object in the array. Therefore NSArray cannot find it.
You will need to loop through the array and determine where the object is located, then you simply remove it by using removeObjectAtIndex:

finding a number in array

I have an Array {-1,0,1,2,3,4...}
I am trying to find whether an element exist in these number or not, code is not working
NSInteger ind = [favArray indexOfObject:[NSNumber numberWithInt:3]];
in ind i am always getting 2147483647
I am filling my array like this
//Loading favArray from favs.plist
NSString* favPlistPath = [[NSBundle mainBundle] pathForResource:#"favs" ofType:#"plist"];
NSMutableDictionary* favPlistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:favPlistPath];
NSString *favString = [favPlistDict objectForKey:#"list"];
NSArray *favList = [favString componentsSeparatedByString:#","];
//int n = [[favList objectAtIndex:0] intValue];
favArray = [[NSMutableArray alloc] initWithCapacity:100];
if([favList count]>1)
{
for(int i=1; i<[favList count]; i++)
{
NSNumber *f = [favList objectAtIndex:i];
[favArray insertObject:f atIndex:(i-1)];
}
}
That's the value of NSNotFound, which means that favArray contains no object that isEqual: to [NSNumber numberWithInt:3]. Check your array.
After second edit:
Your favList array is filled with NSString objects. You should convert the string objects to NSNumber objects before inserting them in favArray:
NSNumber *f = [NSNumber numberWithInt:[[favList objectAtIndex:i] intValue]];