How to check whether data or object already exist in PList, iPhone? - iphone

I can add and remove an object or data in PList successfully but I wanna know that the data or an object already exist in PList. my code is
NSUInteger countObjectsFromPList;
countObjectsFromPList = [[mdict allKeys] count];
NSLog(#"objects in PList %d", countObjectsFromPList);
for(int i=0; i <= countLawsFromPList; i++){
NSLog(#"\n\n\n%d\n\n\n", i);
//if([objectName isEqualToString:[[mdict allKeys] objectAtIndex:i]])
if(objectName ==[[mdict allKeys] objectAtIndex:i]){
NSLog(#"Already exists");
//NSLog("String is equal");
}
else {
NSLog(#"Added to Favorites");
}
}
Please any one help me to over come this. thanks

id object = [mdict objectForKey:key];
BOOL exists = (object != nil);
Edit: apparently that wasn't clear enough.
Basically with objectForKey you're just telling the dictionary "could you please give me the object for my key key"? If the object is there for that key, the returning value will be non-nil. Otherwise it will be nil. That's why you check for object != nil in order to know if that object exists in the dictionary for your key. goes to take more coffee

Thanks for all the code answers, but they turned out to not be helpful for me. I corrected my code to be:
mdict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self doccumentspath]];
NSUInteger countObjectsFromPList = [[mdict allKeys] count];
NSLog(#"Objects in PList %d", countObjectsFromPList);
for(int i=0; i < countObjectsFromPList; i++){
NSLog(#"\n\n\n%d\n\n\n", i);
NSLog(#"from viewWillAppear- Object Name- %#", object);
if([object isEqualToString:[[mdict allKeys] objectAtIndex:i]]){
NSLog(#"Already exists");
exists = YES;
NSLog(#"The value of the bool is %#\n", (exists ? #"YES" : #"NO"));
}
}
What I had to do is to remove the = in the for loop. Now it's working fine.

Related

how to remove NULL values from NSMutableArray? ios

i have array of birthdates as array is getting filled from facebook so there are some friends whos birthdates are private so it contain NULL how to convert that array like empty string wherever there is null value the array is like below
"<null>",
"10/29/1988",
"11/13",
"03/24/1987",
"04/25/1990",
"03/13",
"01/01",
"<null>",
"12/15/1905",
"07/10",
"11/02/1990",
"12/30/1990",
"<null>",
"07/22/1990",
"01/01",
"07/17/1989",
"08/28/1990",
"01/10/1990",
"06/12/1990",
The null values appear to be string literals #"<null>" rather than the NSNull objects typically used to represent nils in Cocoa collections. You can filter them out by using NSArray's filteredArrayUsingPredicate method:
NSArray *filtered = [original filteredArrayUsingPredicate:pred];
There are several ways of making the pred, one of them is
NSPredicate *pred = [NSPredicate predicateWithBlock:^BOOL(id str, NSDictionary *unused) {
return ![str isEqualToString:#"<null>"];
}];
You have to use this to remove the actual [NSNull null] value.
[array removeObjectIdenticalTo:[NSNull null]];
This works for me:
NSMutableArray *array = [NSMutableArray arrayWithObjects:
#"<null>",
#"10/29/1988",
#"11/13",
#"03/24/1987",
#"04/25/1990",
#"03/13",
#"01/01",
#"<null>",
#"12/15/1905",
#"07/10",
#"11/02/1990",
#"12/30/1990",
#"<null>",
#"07/22/1990",
#"01/01",
#"07/17/1989",
#"08/28/1990",
#"01/10/1990",
#"06/12/1990", nil];
NSLog(#"%d", [array count]);
NSString *nullStr = #"<null>";
[array removeObject:nullStr];
NSLog(#"%d", [array count]);
In order to remove null values use :
[yourMutableArray removeObjectIdenticalTo:[NSNull null]];
You don't need iterate over.
for(int i = 0;[yourMutableArray count] > 0;i++){
if([yourMutableArray isKindOfClass:[NSNull class]]){ // indentifies and removes null values from mutable array
[yourMutableArray removeObjectAtIndex:i];
// or
[yourMutableArray replaceObjectAtIndex:i withObject:#"No date available"];
NSLog(#"*** %#",yourMutableArray);
}
}
For json response I removed null values like this
NSArray *arr = [NSArray arrayWithObjects:_IDArray, _TypeArray, _NameArray, _FlagArray, nil];
for (int i=0; i<_integer; i++) {
// My json response assigned to above 4 arrayes
//Now remove null values
//Remove null values
for (int j=0; j<arr.count; j++) {
for (NSMutableArray *ar in arr) {
if ([[ar objectAtIndex:i] isKindOfClass:[NSNull class]] || [[ar objectAtIndex:i] isEqualToString:#"null"]) {
[ar addObject:#""];//Add empty value before remove null value
[ar removeObjectAtIndex:i];
}
}
}
}
Now remove empty values
//Add arrays to mutable array to remove empty objects
NSArray *marr = [NSArray arrayWithObjects:_IDArray, _TypeArray, _NameArray, _FlagArray, nil];
//Remove empty objects from all arrays
for (int j=0; j<marr.count; j++) {
for (int i=0; i<[[marr objectAtIndex:j] count]; i++) {
if ([[[marr objectAtIndex:j] objectAtIndex:i] isEqualToString:#""]) {
[[marr objectAtIndex:j] removeObjectAtIndex:i];
}
}
}

Search String into NSArray based on charcters order?

My Problem Scenario is like this. I have an NSMutableArray ( Every Object is Nsstring). I have a UItextField ( as Client said) for Search.
I want know how to Search String into NSMutableArray like this
if I type A into textfield only those Content come from NSMutableArray which start From A.
if I type AB into TextField only those Content Comes from NSMutableArray which is started from AB..
....
I am Trying NSRange Concept I like share Mycode
~
for (int i=0; i<[[localTotalArrayForAwailable objectForKey:#"PUNCH"] count]; i++)
{
NSString *drinkNamePuch= [[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i] drinkNames];
NSRange titleResultsRange = [drinkNamePuch rangeOfString:searchText options:( NSCaseInsensitiveSearch)];
if (titleResultsRange.length>0)
{
[searchArraypuch addObject:[[localTotalArrayForAwailable objectForKey:#"PUNCH"] objectAtIndex:i]];
[copyListOfItems setValue:searchArraypuch forKey:#"PUNCH"];
}
}
~
Based on this code search not working proper as i need.
Thanks
If you're trying to find all of the strings that match your searchText from the beginning, then you should check:
if ( titleresultsRange.location == 0 )
Other than that, I am not sure what is "not working proper", you need to provide a better explanation of what your expected results are, and what your actual results are.
Do this;
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"SELF BEGINSWITH[cd] %#", searchText];
NSArray* filteredStrings = [[localTotalArrayForAwailable objectForKey:#"PUNCH"] filteredArrayUsingPredicate:predicate];
In filteredStrings you got all the strings that begins with searchText.
You might find Predicate Programming Guide helpful.
try this logic....it is working
NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:#"aa",#"bbb",#"bb",#"cc",#"dd",#"ee",#"ff",#"gg",#"hh",#"ii", nil];
NSMutableArray *arrNew = [[NSMutableArray alloc]init];
NSString *strSearch = #"cccc";
int k = strSearch.length;
for (int i=0; i<[arr count]; i++) {
for (int j=0; j<k; j++) {
if (k<=[[arr objectAtIndex:i] length]) {
if ([strSearch characterAtIndex:j] != [[arr objectAtIndex:i]characterAtIndex:j]) {
break;
}
else if(j == k-1){
[arrNew addObject:[arr objectAtIndex:i]];
}
}
}
}
NSLog(#"%#",[arrNew description]);
You can use these methods, which are provided by NSArray/NSMutableArray:
In NSArray see section "Finding Objects in an Array" for filtering methods starting with "indexesOfObjects...", e.g. indexesOfObjectsPassingTest:
In NSArray see section "Deriving New Arrays" for the method filteredArrayUsingPredicate:
In NSMutableArray there is a method filterUsingPredicate:
For narrowing the results you can continue applying the filtering consecutively to the filtered arrays or index sets.
Example with indexesOfObjectsPassingTest: using a block:
NSArray *strings = [NSArray arrayWithObjects:#"A", #"a", #"aB", #"AbC", #"Bag", #"Babc", #"baCK", #"", #"dba", nil];
NSString *searchString = #"Ab";
BOOL (^startsWithPredicate)(id, NSUInteger, BOOL*) = ^BOOL (id obj, NSUInteger idx, BOOL *stop) {
NSString *string = (NSString *) obj;
NSRange range = [string rangeOfString:searchString options:NSCaseInsensitiveSearch];
return (range.location == 0);
};
NSIndexSet *indexSet = [strings indexesOfObjectsPassingTest:startsWithPredicate];
NSLog(#"Strings found: %#", [strings objectsAtIndexes:indexSet]);
Output:
Strings found: (
aB,
AbC
)

How to get index in an NSArray?

NSMutableArray*array = [[NSMutableArray alloc]init];
NSArray*Somearray = [NSArray arrayWithObjects:1st Object,2ndObject,3rd Object,4th object,5th Object,nil];
In the above array 1st Object,2ndObject,3rd Object,4th object,5th Object having val,content,conclusion in each index.
for(int i=0;i<[Somearray count];i++)
{
______________
Here the code is there to give each index ,that is having val,content,conclusion ..
After that val,content,conclusion in each index will be add to Dict..
____________
NSDictionary *Dict = [NSDictionary dictionaryWithObjectsAndKeys:val,#"val",content,#"content",conclusion,#"conclusion",nil];
//Each time adding dictionary into array;
[array addObject:Dict];
}
The above Dictionary is in for loop and the keyvalue pairs will be add 5 times(Somearray Count).Now array is having in
array = [{val="1.1 this is first one",content="This is the content of 0th index",conclusion="this is the conclusion of 0th index"},{val="1.2 this is first one",content="This is the content of 1st index",conclusion="this is the conclusion of 1st index"},____,____,______,{val="1.5 this is first one",content="This is the content of 4th index",conclusion="this is the conclusion of 4th index"},nil];
Now i am having NSString*string = #"1.5";
Now i need the index where val is having 1.5 in it.How to send the str in to array to find the the index.
Can anyone share the code please.
Thanks in advance.
Use method indexOfObject
int inx= [array indexOfObject:#"1.5"];
For Find index particular key value.
int inx;
for (int i=0; i<[array count]; i++) {
if ([[[array objectAtIndex:i] allKeys] containsObject:#"val"]) {
inx=i;
break;
}
}
The method you are looking for is -[NSArray indexOfObjectPassingTest:]. You would use it like this:
NSUInteger i = [array indexOfObjectPassingTest:^(id obj, NSUInteger idx, BOOL *stop) {
return [[id objectForKey:#"val"] rangeOfString:#"1.5"].location != NSNotFound;
}];
If you just want to check that val starts with "1.5" you would use hasPrefix: instead.
Try this -
NSArray *valArray = [array valueForKey:#"val"];
int index = [valArray indexOfObject:#"1.5"];
Appended answer given by Mandeep, to show you the magic of key value coding ;)
NSUInteger idx = UINT_MAX;
NSCharacterSet* spaceSet = [NSCharacterSet whitespaceCharacterSet];
for(int i=0,i_l=[Yourarray count];i<i_l;i++) {
NSString* s_prime = [[Yourarray objectAtIndex:i] valueForKey:#"val"];
if ([s_prime length] < 4) {
continue;
}
NSString *subString = [[s_prime substringToIndex:4] stringByTrimmingCharactersInSet:spaceSet];
// NSLog(#"index %#",s);
if ([subString isEqualToString:secretNumber]){
idx = i;
break;
}
}
if (idx != UINT_MAX) {
// NSLog(#"Found at index: %d",idx);
} else {
// NSLog(#"Not found");
}

How to rename a Key in NSMutableDictionary?

I am having a NSMutableDictionary. I have to dynamically rename any Key in the dictionary to a new value, in my code.. I can't find any built-in API to do this..
How can I do this? Is there any built-in API available to do this?
Thanks everyone..
// assumes that olkdey and newkey won't be the same; they can't as
// constants... but...
[dict setObject: [dict objectForKey: #"oldkey"] forKey: #"newkey"];
[dict removeObjectForKey: #"oldkey"];
Think about what "directly editing an existing key" means. A dictionary is a hash; it hashes the contents of the keys to find a value.
What happens if you were to change the contents of a key? The key would need to be rehashed (and the dictionary's internal structures re-balanced) or the value would no longer be retrievable.
Why do you want to edit the contents of a key in the first place? I.e. what problem does that solve that the above does not?
This should work:
- (void) renameKey:(id<NSCopying>)oldKey toKey:(id<NSCopying>)newKey{
NSObject *object = [dictionary objectForKey:oldKey];
[object retain];
[dictionary removeObjectForKey:oldKey];
[dictionary setObject:object forKey:newKey];
[object release];
}
This does exactly the same as bbum's answer but, if you remove the old key first (like in this example) then you have to retain the object temporarily otherwise it might get deallocated in the way ;)
Conclusion: Unless you need explicitly to remove the old key first do as bbum.
#interface NSMutableDictionary (KAKeyRenaming)
- (void)ka_replaceKey:(id)oldKey withKey:(id)newKey;
#end
#implementation NSMutableDictionary (KAKeyRenaming)
- (void)ka_replaceKey:(id)oldKey withKey:(id)newKey
{
id value = [self objectForKey:oldKey];
if (value) {
[self setObject:value forKey:newKey];
[self removeObjectForKey:oldKey];
}
}
#end
This also handles the case where the dictionary doesn't have a value for the key nicely.
I have to navigate a complete JSON response object that holds fields, sub-dictionaries and sub-arrays. All because one of the JSON fields is called "return" which is an iOS reserved word, so can't be used with the JSONModel Cocoa Pod.
Here's the code:
+ (id) sanitizeJSON:(id) dictIn {
if (dictIn) //check not null
{
// if it's a dictionary item
if ([dictIn isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *dictOut = [dictIn mutableCopy];
// Do the fix replace "return" with "not_return"
if ([dictOut objectForKey: #"return"])
{[dictOut setObject: [dictIn objectForKey: #"return"] forKey: #"not_return"];
[dictOut removeObjectForKey: #"return"];}
// Continue the recursive walk through
NSArray*keys=[dictOut allKeys]; //get all the keys
for (int n=0;n<keys.count;n++)
{
NSString *key = [keys objectAtIndex:n];
//NSLog(#"key=%# value=%#", key, [dictOut objectForKey:key]);
if (([[dictOut objectForKey:key] isKindOfClass:[NSDictionary class]]) || ([[dictOut objectForKey:key] isKindOfClass:[NSArray class]]))
{
// recursive call
id sanitizedObject = [self sanitizeJSON:[dictOut objectForKey:key]];
[dictOut removeObjectForKey: key];
[dictOut setObject:sanitizedObject forKey:key];
// replace returned (poss modified) item with this one
}
}
return dictOut; //return dict
}
else if ([dictIn isKindOfClass:[NSArray class]]) //Or if it's an array item
{
NSMutableArray *tempArray = [dictIn mutableCopy];
// Do the recursive walk across the array
for (int n=0;n< tempArray.count; n++)
{
// if array item is dictionary
if (([[tempArray objectAtIndex:n] isKindOfClass:[NSDictionary class]]) || ([[tempArray objectAtIndex:n] isKindOfClass:[NSArray class]]))
{
// recursive call
id sanitizedObject = [self sanitizeJSON:[tempArray objectAtIndex:n]];
// replace with the possibly modified item
[tempArray replaceObjectAtIndex:n withObject:sanitizedObject];
}
}
return tempArray; //return array
}
return dictIn; //Not nil or dict or array
}
else
return dictIn; //return nil
}

get the array index in for statement in objective-c

I am stuck in a stupid mess...
I want to get not only the value of an array but also the index of the values.
In PHP it's simple: foreach($array as $key->$value) Here $key will contain the index value.
Isn't there a similar approach in objective c?
How else could I achieve this?
Please help! :((
Arrays not like in php are numbered 0-size of array. I guess you talking about dictionary's. If so you can get array of key with [dict allKeys].
so something like this should work:
for(id key in [dict allKeys]){
id value = [dict objectForKey:key];
}
If you're on iOS4 you can do
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
{
NSLog(#"%# is at index %u", obj, idx);
}];
on iOS 3.x you can do
NSUInteger idx = 0;
for (id obj in array)
{
NSLog(#"%# is at index %u", obj, idx);
idx++
}
for (i=0;i<array.count;i++)
{
NSLog(#"Index=%d , Value=%#",i,[array objectAtIndex:i]);
}
Use this its simpler...
hAPPY cODING...
I'm unable to test it, but I think I did do something similar the other night. From this wiki it looks like you can do something like
for(id key in d) {
NSObject *obj = [d objectForKey:key]; // We use the (unique) key to access the (possibly non-unique) object.
NSLog(#"%#", obj);
}
int arraySize = array.count;
// No need to calculate count/size always
for (int i=0; i<arraySize; i++)
{
NSLog(#"Index=%d , Value=%#",i,[array objectAtIndex:i]);
}