Get index of array object [closed] - iphone

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
This is the code I'm trying to finish
-(IBAction)theButtonIsSelected:(id)sender {
NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:#"Yes" forKey:#"Favorite"];
NSString *nameString = [mutDict valueForKey:#"Name"];
NSArray *allObjects;
allObjects = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjects];
int index;
//I think I just need a little piece right here to set the current allObjectsIndex to match nameString?
[tmpMutArr replaceObjectAtIndex:index withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
allObjects = nil;
allObjects = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjects writeToFile:path atomically:YES];
}
This is my question:
if (what I'm trying to do above can be done) {
How to finish it?
} else {
How to make a function to change the "Favorite" key's value of plist object,
when detailsDataSource not always containing the complete list of objects?
That's why I'm trying to include allObjects and index in this code.
}
EDIT:
Code now look like this:
NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithDictionary:[detailsDataSource objectAtIndex:detailIndex]];
[mutDict setObject:#"Yes" forKey:#"Favorite"];
NSString *nameString = [[detailsDataSource objectAtIndex:detailIndex] valueForKey:#"Name"];
NSArray *allObjectsArray = [[NSArray alloc] initWithContentsOfFile:path];
NSMutableArray *tmpMutArr = [NSMutableArray arrayWithArray:allObjectsArray];
if(int i=0;i<[tmpMutArr count];i++)
//Errors ^here and here^
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([tempDict valueForKey:#"Name" == [NSString stringWithFormat:#"#%", nameString];) //Is this correct?
{
index = i; //index of dictionary
}
}
}
[tmpMutArr replaceObjectAtIndex:i withObject:[NSDictionary dictionaryWithDictionary:mutDict]];
allObjectsArray = nil;
allObjectsArray = [[NSArray alloc] initWithArray:tmpMutArr];
[allObjectsArray writeToFile:path atomically:YES];
Errors: 1 Expected expression 2 undeclared identifier 'i' how to declare I and fix the other error?

You can get index of dictionary like this:
if(int i=0;i<[tmpMutArr count];i++)
{
if([[tmpMutArr objectAtIndex:i] isKindOfClass:[NSDictionary class]])
{
NSMutableDictionary *tempDict = [tmpMutArr objectAtIndex:i];
if([tempDict objectForKey:#"Favorite")
{
index = i; // here u have your index of dictionary
}
}
}

Related

Retrive data of address book and display in string format [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
Hi I am developing an apps in that I got one requirement where I have a button action method when I click the button I should retrive whole address book contacts and display in the form of string how do i do this can anyone tel me with code. I am not able to this from couple of days.
I dont want to navigate using ABPeoplePickerNavigationController and access it
,What all I need is click on button access all contact and display in the form of string.
Try this it works for iOS 6 as well as iOS 5.0 or older:
First add the following frameworks in Link Binary With Libraries
AddressBookUI.framework
AddressBook.framework
Them Import
#import <AddressBook/ABAddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
Then use the following code
ABAddressBookRef addressBook = ABAddressBookCreate();
__block BOOL accessGranted = NO;
if (ABAddressBookRequestAccessWithCompletion != NULL) { // We are on iOS 6
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
accessGranted = granted;
dispatch_semaphore_signal(semaphore);
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
dispatch_release(semaphore);
}
else { // We are on iOS 5 or Older
accessGranted = YES;
[self getContactsWithAddressBook:addressBook];
}
if (accessGranted) {
[self getContactsWithAddressBook:addressBook];
}
// Get the contacts.
- (void)getContactsWithAddressBook:(ABAddressBookRef )addressBook {
NSArray *arrayOfPeople = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger index = 0;
NSMutableArray *firstNames = [[NSMutableArray alloc] init];
for(index = 0; index <= ([arrayOfPeople count] - 1); index++){
ABRecordRef currentPerson = (__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index];
NSString *currentFirstName = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty);
// If first name is empty then don't add to the array
if (![currentFirstName length] == 0) {
[firstNames addObject: currentFirstName];
}
}
//OPTIONAL: Use the following line to sort the first names alphabetically
NSArray *sortedFirstNames = [firstNames sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
NSLog(#"Total Count = %d \n Sorted By Name = %#", [sortedFirstNames count], sortedFirstNames);
}
I tested this and it works.
try this for .
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *people = (NSArray*)ABAddressBookCopyArrayOfAllPeople(addressBook);
for(id person in people){
NSString *name = [NSString stringWithFormat:#"%# %#",(NSString *)ABRecordCopyValue( person, kABPersonFirstNameProperty ),(NSString *)ABRecordCopyValue( person, kABPersonLastNameProperty )];
//fetch multiple phone nos.
ABMultiValueRef multi = ABRecordCopyValue(person, kABPersonPhoneProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multi); j++) {
NSString* phone = (NSString*)ABMultiValueCopyValueAtIndex(multi, j);
[numbersArray addObject:phone];
[phone release];
}
/fetch multiple email ids.
ABMultiValueRef multiemail = ABRecordCopyValue(person, kABPersonEmailProperty);
for (CFIndex j=0; j < ABMultiValueGetCount(multiemail); j++) {
NSString* email = (NSString*)ABMultiValueCopyValueAtIndex(multiemail, j);
NSLog(#"Email=%#",email);
}
}
and you have to alloc your array before you use. in viewDidLoad method write this for alloc array
numbersArray=[[NSMutableArray alloc] init];

I want to sort my array in ascending order [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Array: (2007-99 , 2001-96, 2005-93)
Sorted Output should be: (2005-93, 2001-96, 2007-99)
Please help me out.
You need to write a custom comparator to do something like this. In the method below, I get the location of the dash with rangeOfString, then get the substring starting 1 position further into the string, then convert that to an int to do the comparison:
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#"2007-07",#"2005-01",#"2004-09",#"2003-02", nil];
NSArray *sortedArray = [arr sortedArrayUsingComparator: ^(NSString *s1, NSString *s2) {
if ([[s1 substringFromIndex:[s1 rangeOfString:#"-"].location + 1] intValue] > [[s2 substringFromIndex:[s2 rangeOfString:#"-"].location + 1] intValue]) {
return (NSComparisonResult)NSOrderedDescending;
}
if ([[s1 substringFromIndex:[s1 rangeOfString:#"-"].location + 1] intValue] < [[s2 substringFromIndex:[s2 rangeOfString:#"-"].location + 1] intValue]) {
return (NSComparisonResult)NSOrderedAscending;
}
return (NSComparisonResult)NSOrderedSame;
}];
NSLog(#"%#",sortedArray);
You can sort this using a custom block (note that I assume that all of your numbers are formatted correctly):
NSArray *rollNumbers = [NSArray arrayWithObjects:#"2007-99", #"2001-96", #"2005-93", nil];
NSArray *sortedRollNumbers = [rollNumbers sortedArrayUsingComparator:^NSComparisonResult(NSString *roll1, NSString *roll2) {
NSArray *roll1Components = [roll1 componentsSeparatedByString:#"-"];
NSArray *roll2Components = [roll2 componentsSeparatedByString:#"-"];
NSNumber *roll1Number = [NSNumber numberWithInt:[[roll1Components objectAtIndex:1] intValue]];
NSNumber *roll2Number = [NSNumber numberWithInt:[[roll2Components objectAtIndex:1] intValue]];
return [roll1Number compare:roll2Number];
}];
NSLog(#"%#", sortedRollNumbers);
Output:
(
"2005-93",
"2001-96",
"2007-99" )
You can sort your array like this :
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:#"2007-07",#"2005-01",#"2004-09",#"2003-02", nil];
NSMutableArray *marks = [[NSMutableArray alloc]init];
for (int i = 0; i < arr.count; i++)
{
NSArray *sep = [[arr objectAtIndex:i] componentsSeparatedByString:#"-"];
[marks addObject:[sep objectAtIndex:1]];
}
NSSortDescriptor *sortDesc = [[NSSortDescriptor alloc] initWithKey:#"" ascending:NO];
[marks sortUsingDescriptors:[NSArray arrayWithObject:sortDesc]];
NSMutableArray *sortedFinalArray = [[NSMutableArray alloc]init];
for (int i = 0; i < marks.count; i++)
{
for (int k = 0; k < arr.count; k++)
{
NSRange aRange = [[arr objectAtIndex:i] rangeOfString:[marks objectAtIndex:k]];
if (!(aRange.location == NSNotFound))
{
[sortedFinalArray addObject:[arr objectAtIndex:k]];
}
}
}
In order that you can sort your array, the elements of the array have to be compared pairwise to find out their ordering. Your specific ordering is custom, so you have to write a compare method (e.g. named compare:) by yourself, and then you can use [arr sortUsingSelector:#selector(compare:)]; to sort your array.
Now the compare: method has to be known to the elements of the array, because each element uses it to compare it to another element of the same class. So either you define a new class for your elements that implements the compare method, or you leave them as NSStrings, buth the you have to define a category that implements the compare: method.
The compare: method itself could look like this (pseudo code):
-(NSComparisonResult) compare: (MyString *) myString {
if
(self.the_last_2_characters_interpreted_asNumber <
myString.the_last_2_characters_interpreted_asNumber)
return NSOrderedAscending;
else if
(self.the_last_2_characters_interpreted_asNumber ==
myString.the_last_2_characters_interpreted_asNumber)
return NSOrderedSame;
else
return NSOrderedDescending;
}

Search function in iphone? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
My array is like
{
"Samsung Tab",
"Samsung Note",
"Samsung Galaxy",
"Samsung Galaxy Pro",
"Nokia Lumia",
"Nokia 5130",
"Sony Xperia"
}
Some thing like that. I have text box type GALAXY and click the button. I want to show only Samsung Galaxy , Samsung Galaxy Pro in next list view. Can anyone help me?.
Use predicate to filter an array like below
NSArray *arrayMobiles= [NSArray arrayWithObjects:#"Samsung Tab",#"Samsung Note", #"Samsung Galaxy", #"Samsung Galaxy Pro", #"Nokia Lumia", #"Nokia 5130",#"Nokia 5130",#"Sony Xperia", nil];
NSString *strSearchkey = #"GALAXY";
NSPredicate *containPred = [NSPredicate predicateWithFormat:#"SELF contains[cd] %#", strSearchkey];
NSArray *arrayFilter = [arrayMobiles filteredArrayUsingPredicate:containPred];
NSLog(#"%#",arrayFilter);
//output
"Samsung Galaxy",
"Samsung Galaxy Pro"
Take Two NSMutableArray and add one array to another array in ViewDidLoad method such like,
self.listOfTemArray = [[NSMutableArray alloc] init]; // array no - 1
self.ItemOfMainArray = [[NSMutableArray alloc] initWithObjects:#"YorArrayList", nil]; // array no - 2
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray]; // add 2array to 1 array
And Write following delegate Method of UISearchBar
- (BOOL) textFieldDidChange:(UITextField *)textField
{
NSString *name = #"";
NSString *firstLetter = #"";
if (self.listOfTemArray.count > 0)
[self.listOfTemArray removeAllObjects];
if ([searchText length] > 0)
{
for (int i = 0; i < [self.ItemOfMainArray count] ; i = i+1)
{
name = [self.ItemOfMainArray objectAtIndex:i];
if (name.length >= searchText.length)
{
firstLetter = [name substringWithRange:NSMakeRange(0, [searchText length])];
//NSLog(#"%#",firstLetter);
if( [firstLetter caseInsensitiveCompare:searchText] == NSOrderedSame )
{
// strings are equal except for possibly case
[self.listOfTemArray addObject: [self.ItemOfMainArray objectAtIndex:i]];
NSLog(#"=========> %#",self.listOfTemArray);
}
}
}
}
else
{
[self.listOfTemArray addObjectsFromArray:self.ItemOfMainArray ];
}
[self.tblView reloadData];
}
}
Output Show in your Consol.
This code might helpful for you...thanks :)
This may help you
- (void)searchArrayFrom: (NSString *) matchString{
NSString *upString = [matchString uppercaseString];
if (searchArray){[searchArray release];searchArray = nil;}
searchArray = [[NSMutableArray alloc] init];
NSMutableArray *temp = [internalEvents copy];
for (int i=0;i<[temp count];i++)
{
NSString *str = [internalEvents objectAtIndex:i];
// Add everyone when there's nothing to match to
if ([matchString length] == 0)
{
[searchArray addObject:str];
continue;
}
// Add the person if the string matches
NSRange range = [[str uppercaseString] rangeOfString:upString];
if (range.location != NSNotFound) {
[searchArray addObject:str];
}
}
[temp release];
temp = nil;
[tblView reloadData];
}
You can use the below given function :
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring
{
for (int i = 0; i < [yourArray count]; i++)
{
NSString *curString = [[yourArray objectAtIndex:i]lowercaseString];
NSString *searchString = [substring lowercaseString];
if ([curString rangeOfString:curStringSmall].location == NSNotFound)
{
}
else
{
//This means searched text is found in your array. you can store it in new array. Which will give you only the search criteria matched element.
}
}
}
You need to call this function on the click of your search button. Like :
-(void)searchButtonClicked
{
[self searchAutocompleteEntriesWithSubstring:txtSearch.text];
}
you might use the NSPrediction
NSString * SEARCH_KEYWORD = #"s";
NSMutableArray *array =
[NSMutableArray arrayWithObjects:#"Bill", #"Ben", #"Chris", #"Melissa", nil];
NSPredicate *sPredicate =
[NSPredicate predicateWithFormat:#"SELF contains[c] '%#'", SEARCH_KEYWORD];
[array filterUsingPredicate:sPredicate];
// array now contains { #"Chris", #"Melissa" }

Tread 9: EXC_BAD_ACCESS [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I get this message "Tread 9: EXC_BAD_ACCESS (code=1, address=0x70000010) in this method (but this bug is being created only when in another thread file is being downloaded ):
- (NSMutableDictionary *) getDictionaryAllStatin:(sqlite3*)database
{
if (self._streetsArrey == nil || self._streetsArrey.count <= 0) {
[self getArrayAllStatin:database];
}
/*--------------------------------------------------------------*/
NSMutableDictionary *result1 = [[NSMutableDictionary alloc] init];
for (StreetData *street in _streetsArrey) {
NSString * name = [self deleteContractionWithText:street._name];
NSArray * arr = [name componentsSeparatedByString:#" "];
NSMutableArray *arrm = [[NSMutableArray alloc] initWithArray:arr];
arr = nil;
[arrm addObject:name];
for (NSString *txt in arrm) {
int lengthText = txt.length;
for (int i = 2 ; i <= lengthText; i++) {
NSString * key = [txt substringToIndex:i];
key = [key lowercaseString];
NSMutableDictionary *isSet = [result1 objectForKey:[NSNumber numberWithInt:[key hash]]];
if (isSet == nil) {
isSet = [[NSMutableDictionary alloc]init];
}
[isSet setObject:street forKey:[NSNumber numberWithInt:street._streetId]];
[result1 setObject:isSet forKey:[NSNumber numberWithInt:[key hash]]];
isSet = nil;
key = nil;
}
}
}
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
for (id key in result1) {
NSMutableDictionary *dictionary = [result1 objectForKey:key];
NSArray *arr = [dictionary allValues];
[result setObject:arr forKey:key];
arr = nil;
[dictionary removeAllObjects];
dictionary = nil;
}
[result1 removeAllObjects];
result1 = nil;
/*--------------------------------------------------------------*/
if (result.count > 0) {
_streetsDictionary = result;
result = nil;
return _streetsDictionary;
}else {
_streetsDictionary = nil;
return nil;
}
}
Why do I get this message?
How can I fix it?
The most likely cause for the crash is trying to access an object that has already been deallocated.
Since it seems that the failure arises on the line:
NSMutableDictionary *isSet = [result1 objectForKey:[NSNumber numberWithInt:[key hash]]];
I would suggest splitting the statement down to its component to try and track down which object could actually be the culprit:
NSInteger h = [key hash];
NSNumber n = [NSNumber numberWithInt:h];
...
but this bug is being created only when in another thread file is being downloaded
Also, check if the downloading code and the crashing code have anything in common. The former might be causing the deallocation of an object used in the second.
Hope it helps.

Transforming NSMutableArray values [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I've been looking for this, but can't find the answer.
I have an NSMutableArray with values who_1, what_2, where_3 etc.
I want to transform this into who, what, where etc.
I already have the value of the integer as a variable, and _ is just a string.
What steps should I take to have all these arrayvalues transformed?
NSArray * arrB = [[NSArray alloc]initWithObjects:#"apple_a",#"ball_b",#"cat_c",#"doll_d",nil];
NSMutableArray * arrA = [[NSMutableArray alloc]init];
for(NSString *strData in arrB)
{
NSArray *arr = [strData componentsSeparatedByString:#"_"];
[arrA addObject:[arr objectAtIndex:0]];
}
and this would be your output
arrA:(
apple,
ball,
cat,
doll
)
You need to apply logic for that, You cant find answers to tricky Questions :)
You need to run a loop.
Separate string with '_'
Loop
for(NSString *s in ary)
{
NSArray *a = [s componentsSeparatedByString:#"_"];
[anotherArray addObject:[a objectAtIndex:0]];
}
and update your array..
Following might help you -
NSRange range = [string rangeOfString:#"_"];
NSString *finalString = [originalString substringToIndex:range.location];
you can have this in loop.
Or you can go for componentSeperatedByStrings.
This might help you
NSMutableArray *tmpAry = [[NSMutableArray alloc] init];
for(NSString *_string in _StringAry)
{
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:#"_0123456789"];
_string = [[_string componentsSeparatedByCharactersInSet:charSet] componentsJoinedByString:#""];
[tmpAry addObject: [[_string copy] autorelease]];
}
NSLog(#"%#", tmpAry); // Gives the modified array
[tmpAry release];