I am using NSMutableArray for adding objects.But its add only first 10 objects.
I have code for sharing
for (int j = 0; j<[feedData count]; j++)
{
[sharingItems addObject:[self whatsappdata:[feedData objectAtIndex:j]]];
}
This method return NSString type text.
Please provide me valid solution for this.
Thanks in Advance
-(NSString *)whatsappdata:(NSDictionary *)cellData1
{
NSString *brandName = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"brand_name"]];
NSString *modelName = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"brand_model_name"]];
NSString *version = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"version_name"]];
if ([version isEqualToString: #"<null>"])
{
version = #"";
}
NSString *year = [NSString stringWithFormat:#"%#", [cellData1 objectForKey:#"model_year"]];
if (year == nil || [year isEqualToString:#"0"])
{
year = #"";
}
NSString *inventoryValue = [NSString stringWithFormat:#"%#",[cellData1 objectForKey:#"inventory_type"]];
NSInteger value = [inventoryValue intValue];
NSString *inventoryName;
NSString *msg;
if(value == 1)
{
inventoryName = [NSString stringWithFormat:#"%#", #"Stock"];
i++;
NSString *text2 = [NSString stringWithFormat:#"%d.%# %# %#- %# Single Owner\n",i, brandName, modelName, version, year];
msg = [NSString stringWithFormat:#"%#",text2];
msg= [msg stringByReplacingOccurrencesOfString:#"\n" withString:#"<br/>"];
}
else
{
inventoryName = [NSString stringWithFormat:#"%#", #"Required"];
msg = #"";
}
return msg;
//end data
}
Most probably "fetch limit" has set for 'NSFetchRequest' inside your code.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setFetchLimit:10];//such code you need to find and remove/change fetch limit
you need to allocate memory to array before adding elements
sharingItems = [[NSMutableArray alloc]init];
Related
hello all i am working on a project in which i have to create an array in this format:
{
"1": {
"Child_Gender": "",
"Child_DOB": "",
"Child_tobbacoUse": ""
},
"2": {
"Child_Gender": "",
"Child_DOB": "",
"Child_tobbacoUse": ""
},
but the array i create gives this format
(
{
"Child_DOB" = "";
"Child_Gender" = "";
"Child_tobbacoUse" = "";
},
{
"Child_DOB" = "";
"Child_Gender" = "";
"Child_tobbacoUse" = "";
}
)
i am using the following code:
for (int i = 0; i < arrayChildModel.count; i++)
{
ChildModel *model = [arrayChildModel objectAtIndex:i];
NSString *keyOrder = [NSString stringWithFormat:#"Children_Gender[%d]",i];
NSString *keyQuantity = [NSString stringWithFormat:#"Children_BirthDate[%d]",i];
NSString *keyTobacco = [NSString stringWithFormat:#"Children_HasTobaccoUsage[%d]",i];
//NSString *keyNotes = [NSString stringWithFormat:#"row[%d][description]",i];
childDateOfBirthStr = model.ChildBirthDate ;
childGenderStr = model.ChildGender ;
childTobaccoStr = model.ChildTobaccoUsage;
NSString *string1 = [NSString stringWithFormat:#"%#=%#&",keyOrder,childGenderStr];
NSString *string2 = [NSString stringWithFormat:#"%#=%#",keyQuantity,childDateOfBirthStr];
NSString *string3 = [NSString stringWithFormat:#"%#=%#",keyTobacco,childTobaccoStr];
[stringParams appendString:string1];
[stringParams appendString:string2];
[stringParams appendString:string3];
NSDictionary * ChildDict;
NSArray * ApplicantKeys = [[NSArray alloc]initWithObjects:#"Child_Gender",#"Child_DOB",#"Child_tobbacoUse", nil];
NSArray * ApplicantObjects = [[NSArray alloc]initWithObjects:childGenderStr,childDateOfBirthStr,childTobaccoStr, nil];
ChildDict = [NSDictionary dictionaryWithObjects:ApplicantObjects forKeys:ApplicantKeys];
NSLog(#"Dictionary is %#",ChildDict);
[CompleteArray addObject:ChildDict];
}
NSLog(#"Final Array is %#",CompleteArray);
please help me to convert the output array to the required formatted array
Create one dictionary outer for loop
NSMutableDictionary *dict =[[NSMutableDictionary alloc]init];
add this line before NSLog(#"Dictionary is %#",ChildDict);
[dict setObject:ChildDict forKey:[NSString stringWithFormat:#"%ld",i+1]];
[CompleteArray addObject:dict];
Please check following solution it will give you as expected output.
NSMutableDictionary *resultDic = [NSMutableDictionary new];
for (int i = 0; i < arrayChildModel.count; i++)
{
ChildModel *model = [arrayChildModel objectAtIndex:i];
NSString *keyOrder = [NSString stringWithFormat:#"Children_Gender[%d]",i];
NSString *keyQuantity = [NSString stringWithFormat:#"Children_BirthDate[%d]",i];
NSString *keyTobacco = [NSString stringWithFormat:#"Children_HasTobaccoUsage[%d]",i];
//NSString *keyNotes = [NSString stringWithFormat:#"row[%d][description]",i];
childDateOfBirthStr = model.ChildBirthDate ;
childGenderStr = model.ChildGender ;
childTobaccoStr = model.ChildTobaccoUsage;
NSString *string1 = [NSString stringWithFormat:#"%#=%#&",keyOrder,childGenderStr];
NSString *string2 = [NSString stringWithFormat:#"%#=%#",keyQuantity,childDateOfBirthStr];
NSString *string3 = [NSString stringWithFormat:#"%#=%#",keyTobacco,childTobaccoStr];
[stringParams appendString:string1];
[stringParams appendString:string2];
[stringParams appendString:string3];
NSDictionary * ChildDict = [NSDictionary dictionaryWithObjectsAndKeys:childGenderStr,#"Child_Gender",childDateOfBirthStr,#"Child_DOB",childTobaccoStr,#"Child_tobbacoUse", nil];
NSLog(#"Dictionary is %#",ChildDict);
NSString *resultDicKey = [NSString stringWithFormat:#"%d",i+1];
[resultDic setValue:ChildDict forKey:resultDicKey];
}
NSLog(#"Result dic %#",resultDic);
here is my code. I used NSDictionary and coded to print my json data in my console.but i got error like this:
'NSInvalidArgumentException', reason: '-[__NSCFString objectForKeyedSubscript:]: unrecognized selector sent to instance 0x7c971930'
My code:
if(buttonIndex == 0) {
NSLog(#"OK Button is clicked");
}
else if(buttonIndex == 1) {
if([[textView.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]!=0)
{
if(!self.note)
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newNote = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:context];
NSLog(#"%#",textView.text);
[newNote setValue:textView.text forKey:#"note"];
if([textView.text length]>30)
{
[newNote setValue:[NSString stringWithFormat:#"%#...",[textView.text substringToIndex:25]] forKey:#"title"];
}
else
[newNote setValue:textView.text forKey:#"title"];
[newNote setValue:[NSDate date] forKey:#"mod_time"];
//[newDevice setValue:self.versionTextField.text forKey:#"version"];
//[newDevice setValue:self.companyTextField.text forKey:#"company"];
How to overcome this problem to work and to print my data in my console
Help me out. I am struggling for 2 hours.I googled and change all change.But cant get data in my console. Thanks in advance
I guess you can get data like below this
NSDictionary *monday = jsonResults[#"original"];
NSArray * arrFile = monday[#"files"];
for (NSDictionary *theCourse in arrFile)
{
....
}
Did you checked that received data (i.e., returnData) from sendSynchronousRequest: is returning a plain data?
If the data received is in Base64, you might have to decode this NSData to plain data, and then go ahead with String conversion.
NSData *decodedData = [[NSData alloc] initWithBase64EncodedData:responseData options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *str = [[NSString alloc] initWithData:decodedData encoding:NSUTF8StringEncoding];
// convert Json to NSDictionary
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:returnData options:NSJSONReadingMutableContainers error:nil];
// NSLog(#"%#",jsonResults);
int count = [[jsonResults valueForKey:#"count"] intValue];
NSArray *arrayData = [jsonResults copy];
NSMutableArray *arrayPDFName = [[NSMutableArray alloc]init];
for(int i = 0;i < [arrayData count];i++)
{
NSDictionary *dictOriginal = [[arrayData objectAtIndex:2]valueForKey:#"original"];
int countOriginal = [[dictOriginal valueForKey:#"count"] intValue];
NSLog(#"The countOriginal is - %d",countOriginal);
NSArray *arrayFiles = [[dictOriginal valueForKey:#"files"] copy];
NSLog(#"The arrayFiles are - %#",arrayFiles);
for(int j=0;j<[arrayFiles count];j++)
{
NSString *strCreatedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"created_time"]];
NSString *strLastModifiedTime = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"last_modified_time"]];
NSString *strID = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"id"]];
NSString *strName = [NSString stringWithFormat:#"%#",[[arrayFiles objectAtIndex:j] valueForKey:#"name"]];
NSLog(#"The created_time is - %#",strCreatedTime);
NSLog(#"The last_modified_time is - %#",strLastModifiedTime);
NSLog(#"The is is - %#",strID);
NSLog(#"The name is - %#",strName);
[arrayPDFName addObject:strName];
}
}
So i want to print the users in an NSMutableArray. But the strings keep coming out as nil.
here is what i have:
int users = 0;
- (IBAction)addNewUser:(id)sender {
NSString *string;
string = userNameTextField.text;
[usernameArray insertObject:string atIndex:users];
users++;
[self showUsers];
}
-(void)showUsers{
for (int i = 0; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [NSString stringWithFormat:#"%# ",[usernameArray objectAtIndex:i]];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}
i have also tried
-(void)showUsers{
for (int i = 1; i < users; i++){
NSString *s = textView.text;
NSString *add;
add = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"%# \n %#", s, add];
textView.text = display;
}
}
First of all try using more comprehensive names for the objects. I'm rewriting your code.
Common Causes for the problem : Array not initialized, you are starting your for cycle with int i equal to 1, so you are missing the object at index 0 at your mutable array. Try the following code.
#interface InterfaceName : InterfaceInherits <IfDelegate> {
int usersCount;
NSMutableArray * usernameArray;
}
#implementation InterfaceName
/*There's no more confident way to initialize a variable than in the init method of the class. */
-(id)init{
usersCount = 0;
//You have to be sure that your array is not nil
usernameArray = [NSMutableArray alloc]init]];
return self;
}
- (IBAction)addNewUser:(id)sender {
NSString *username = [usernameTextField text];
[usernameArray insertObject:username atIndex:usersCount];
usersCount++;
//I'll omit the display as I'm not sure what you were doing with it.
}
-(void)showUsers{
for (int i = 0; i < usersCount; i++){
NSString *retrievedUser = [usernameArray objectAtIndex:i];
NSString *display = [NSString stringWithFormat:#"User Retrieved : %#",retrievedUser];
textView.text = display;
}
}
#end
I have a NSDictionary looks like this:
data = {
start = {
name = "abc";
age = "123";
id = AA838DDE;
};
};
how can I parser the dictionary to get individual name, age, and id? Thanks.
NSString *name = dictionary[#"data"][#"start"][#"name"];
I add an other answer because I hate the new Objective-C syntax (sorry #Raphael Olivieira)
NSString *name = [[[[dictionary objectForKey:#"data"] objectForKey:#"start"] objectAtIndex:0] objectForKey:#"name"];
NSLog(#"%#", name);
Longer than the previous answer but you know what you do and you don't code in C.
BTW, using the other syntax :
NSString *name = dictionary[#"data"][#"start"][0][#"name"];
NSLog(#"%#", name);
why don't you simply try:
int arrCount = [[[dictionaryObject valueForKey:#"data"] objectForKey:#"start"] count];
for(int i = 0 ; i < arrCount ; i++)
{
NSString *strName = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"name"];
NSString *strAge = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"age"];
NSString *strID = [[[[dictionaryObject objectForKey:#"data"]
objectForKey:#"start"]
objectAtIndex:i]
objectForKey:#"id"];
NSLog(#"%# - %# - %#", strName, strAge, strID);
}
I am writing an app where I want to collect names and phone numbers from a list and add them into an array. How do I do this? I could retrieve first name and last name, but I don't get how to add a phone number in the below code as it is in a different for loop. It might look simple but I am stuck as I am new.
for (i = 0; i < [list count]; i++)
{
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
NSMutableArray *name = [NSMutableArray array];
if(firstName != nil)
[name addObject:firstName];
if(lastName != nil)
[name addObject:lastName];*/
[self displaynames:name];
ABMultiValueRef mobile=ABRecordCopyValue(contactPerson, kABPersonPhoneProperty);
for (int k=0;k<ABMultiValueGetCount(mobile); k++)
{
NSString *mobileNo = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(mobile, k);
NSLog(#"mobile number: %#",mobileNo);
}
}
- (void)displaynames:(NSMutableArray*)names
{
for (NSMutableArray* name in names)
{
NSLog(#"MyResult:%# %#",[names objectAtIndex:0],[names objectAtIndex:1]);
}
}
So in the above code I am able to get the first name and last name from the list and add them into the array, similarly how do I get mobile phone number and add into the same array and get the result in the displayNames: function as it is another for loop. Can someone please edit the code and tell me what changes I have to make in the above code. Also in the result everything is being displayed twice why so?
NSMutableArray *contactList=[[NSMutableArray alloc] init];
for (int i=0; i<4; i++) {
NSMutableDictionary *contactInfo=[[NSMutableDictionary alloc] init];
for (int i = 0; i < [list count]; i++)
{
NSString *firstName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonFirstNameProperty);
NSString *lastName = (__bridge_transfer NSString *)ABRecordCopyValue(contactPerson, kABPersonLastNameProperty);
if (![firstName isEqualToString:#""]) {
[contactInfo setValue:firstName forKey:#"firstName"];
}
if (![lastName isEqualToString:#""]) {
[contactInfo setValue:lastName forKey:#"lastName"];
}
NSMutableArray *mobileNoArray=[[NSMutableArray alloc] initWithCapacity:ABMultiValueGetCount(mobile)];
ABMultiValueRef mobile=ABRecordCopyValue(contactPerson, kABPersonPhoneProperty);
for (int k=0;k<ABMultiValueGetCount(mobile); k++)
{
NSString *mobileNo = (__bridge_transfer NSString *)ABMultiValueCopyValueAtIndex(mobile, k);
[mobileNoArray addObject:mobileNo];
}
if (mobileNoArray.count!=0) {
[contactInfo setObject:mobileNoArray forKey:#"mobileNo"]
}
}
[contactList addObject:contactInfo];
NSLog(#"contact info == %#",contactInfo);
}
NSLog(#"contact list array is %#",contactList);
So, instead using Array you have to use Dictionary to store FirstName, LastName and MobileNo with keyvalue Pair. If you have multiple user than use Array as upper layer, means add your user dictionary into array and when ever you want a user write the code:
for(NSDictionary *userDic in yourArray)
{
NSString *fName = [userDic valueForKey:#"FirstName"];
...
}
This is one of the way...
You can try to add the user info in a dictionary or create a model user object and store in the array. So all the information stays encapsulated in a single object.
self.users = [NSMutableArray array];
for (i = 0; i < [list count]; i++)
{
NSString *firstName = ...
NSString *lastName = ...
NSString *mobileNumber = ...
NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
if(firstName)
userInfo[#"FirstName"] = firstName;
if(lastName)
userInfo[#"LastName"] = lastName;
if(mobileNumber)
userInfo[#"MobileNumber"] = mobileNumber;
[self.users addObject:userInfo];
}
You can enumerate using
[self.users enumerateObjectsUsingBlock:^(NSDictionary * userInfo, NSUInteger idx, BOOL *stop) {
NSString *firstName = userInfo[#"FirstName"];
NSString *mobileNumber = userInfo[#"MobileNumber"];
}];
Searching for a single user for a name
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"FirstName == %#",#"aUserName"];
NSDictionary *userInfo = [[self.users filteredArrayUsingPredicate:predicate]lastObject];
Try the following steps:
NSMutableArray *firstNames;
NSMutableArray *LastNames;
NSMutableArray *Mobile_numbers;
NSMutableArray *type_array;
NSMutableArray *firstandlast;
........
-(void)get_arr
{
ABAddressBookRef addressBook = ABAddressBookCreate();
NSArray *arrayOfPeople = (__bridge_transfer NSArray *)ABAddressBookCopyArrayOfAllPeople(addressBook);
NSUInteger index = 0;
firstNames = [[NSMutableArray alloc] init];
Mobile_numbers = [[NSMutableArray alloc] init];
type_array=[[NSMutableArray alloc]init ];
LastNames=[[NSMutableArray alloc]init ];
NSMutableArray *firstandlast;
#try
{
for(index = 0; index<=([arrayOfPeople count]-1); index++)
{
ABRecordRef currentPerson = (__bridge ABRecordRef)[arrayOfPeople objectAtIndex:index];
NSString *type;
ABMultiValueRef phones = (ABMultiValueRef)ABRecordCopyValue(currentPerson, kABPersonPhoneProperty);
for (int i=0; i < ABMultiValueGetCount(phones); i++)
{
//NSString *phone = (NSString *)ABMultiValueCopyValueAtIndex(phones, i);
////NSLog(#"%#", phone);
mobileLabel = (NSString*)ABMultiValueCopyLabelAtIndex(phones, i);
//NSLog(#"MOG:%#",mobileLabel);
if([mobileLabel isEqualToString:#"_$!<Mobile>!$_"]||[mobileLabel isEqualToString:#"_$!<Main>!$_"])
{
//NSLog(#"mobile:");
type=#"mobile";
}
else if ([mobileLabel isEqualToString:#"_$!<Work>!$_"])
{
//NSLog(#"Work:");
type=#"Work";
}
else if ([mobileLabel isEqualToString:#"_$!<Home>!$_"])
{
//NSLog(#"Home:");
type=#"Home";
}
else if ([mobileLabel isEqualToString:#"_$!<Other>!$_"] )
{
//NSLog(#"Other:");
type=#"Other";
}
mobile = (NSString*)ABMultiValueCopyValueAtIndex(phones, i);
//NSLog(#"GG:%#",mobile);
mobile = [mobile stringByReplacingOccurrencesOfString:#"-"
withString:#""];
mobile = [mobile stringByReplacingOccurrencesOfString:#"("
withString:#""];
mobile = [mobile stringByReplacingOccurrencesOfString:#")"
withString:#""];
mobile = [mobile stringByReplacingOccurrencesOfString:#" "
withString:#""];
[Mobile_numbers addObject:mobile];
[type_array addObject:type];
NSString *currentFirstName = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonFirstNameProperty);
////NSLog(#"NAME:%#",currentFirstName);
if ([currentFirstName length]!=0)
{
//NSLog(#"NAME:%#",currentFirstName);
[firstNames addObject:currentFirstName];
}
else
{
//NSLog(#"NAME:DUMMY");
currentFirstName=#"";
[firstNames addObject:currentFirstName];
}
NSString *currentLast = (__bridge_transfer NSString *)ABRecordCopyValue(currentPerson, kABPersonLastNameProperty);
////NSLog(#"NAME:%#",currentFirstName);
if ([currentLast length]!=0)
{
//NSLog(#"NAME:%#",currentLast);
[LastNames addObject:currentLast];
}
else
{
//NSLog(#"NAME:DUMMY");
currentLast=#"";
[LastNames addObject:currentLast];
}
NSString *temp_f_l=[NSString stringWithFormat:#"%# %#",currentFirstName,currentLast];
[firstandlast addObject:temp_f_l];
}
NSLog(#"MOB:%#",Mobile_numbers);
NSLog(#"TYPE:%#",type_array);
NSLog(#"FN:%#",firstNames);
NSLog(#"FN:%#",LastNames);
NSLog(#"FN&LN:%#",firstandlast);
}
}
#catch (NSException *exception)
{
//NSLog(#"CATCH");
}
}
In my Application. I am using this code to store Addressbook contents to Array. I hope it help for you.