Create an Array from the xml file - objective-c

My XML format is like this:
<Rows>
<Row>
<style>String</style?
<thumbnail>String</thumbnail>
</Row>
<Row>
<style>String</style?
<thumbnail>String</thumbnail>
</Row>
</Rows>
How do i create an NSMutableArray like this ({style = "value"; thumbnail = "value";}.....)
Here is my code:
-(void) parser:(NSXMLParser *) parser didStartElement:(NSString *) elementName namespaceURI:(NSString *) namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"style"]) {
element = [NSString stringWithString:elementName];
if (!soapResults) {
soapResults = [[NSMutableString alloc] init];
}
elementFound = YES;
}
if ([elementName isEqualToString:#"thumbnail1"]) {
element = [NSString stringWithString:elementName];
if (!soapResults) {
soapResults = [[NSMutableString alloc] init];
}
elementFound = YES;
}
}
-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
if (elementFound) {
[soapResults appendString:string];
}
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI: (NSString*)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"style"]) {
[rowDict setValue:soapResults forKey:#"style"];
elementFound = NO;
soapResults = nil;
}
if ([elementName isEqualToString:#"thumbnail1"]) {
[rowDict setValue:soapResults forKey:#"thumbnail1"];
elementFound = NO;
soapResults = nil;
}
}
I'm getting wrong format if I'm doing like this please help me out
Thanks in Advance.

create one object class let say SampleObj
*SampleObj.h*
#interface SampleObj : NSObject
{
NSString *style;
NSString *thumbnail;
}
#property (nonatomic,retain) NSString *style,*thumbnail;
*SampleObj.m*
#implementation SampleObj
#synthesize style,thumbnail;
//dealloc your synthesized value;
do parsing like this.
NSArray *array=[theXML componentsSeparatedByString:#"<Rows>"];
for(int i=1;i<[array count];i++)
{
NSArray *arrayRow=[theXML componentsSeparatedByString:#"<Row>"];
for(int j=1;j<[arrayRow count];j++)
{
SampleObj *custobj = [[SampleObj alloc] init];
NSString *str=[arrayRow objectAtIndex:i];
NSArray *arr1=[str componentsSeparatedByString:#"<style>"];
NSString *data=[arr1 objectAtIndex:1];
NSRange ranfrom=[data rangeOfString:#"</style>"];
custobj.style =[data substringToIndex:ranfrom.location];
arr1=[str componentsSeparatedByString:#"< thumbnail >"];
data=[arr1 objectAtIndex:1];
ranfrom=[data rangeOfString:#"</thumbnail >"];
custobj.thumbnail=[data substringToIndex:ranfrom.location];
[yourarray addObject:custobj];
[custobj release]
}
}
if you want to use the object:
SampleObj *custobj = [yourarray objectAtIndex:rowPosition];
NSLog(#"style : %#", custobj.style);
NSLog(#"thumbnail : %#", custobj.thumbnail);
Hope it will help. sorry for any typo.

Related

Parse xml via NSString with NSXMLParser

I try to parse an NSString in XML format using the NSXMLParser class but I unable to analyze it all.
it just displays the elements of the first tag (element)
When I parse the content inside an XML file i get all elements.
#import "Parser.h"
#import "DeviceConfig.h"
#implementation Parser
#synthesize curElement;
#synthesize value;
#synthesize defaultValue;
-(id) initWithXMLData: (NSString*) data {
if(self == [super init]) {
xmlData = data;
NSData* xmlNSData = [xmlData dataUsingEncoding:NSUTF8StringEncoding];
cameraOptions = [[NSMutableDictionary alloc] init];
parser = [[NSXMLParser alloc] initWithData:xmlNSData];
[parser setDelegate: self];
[parser parse];
}
return self;
}
- (NSMutableDictionary*) getCameraOptions {
return cameraOptions;
}
- (void) parser: (NSXMLParser*) parser didStartElement:(nonnull NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName attributes:(nonnull NSDictionary<NSString *,NSString *> *)attributeDict {
NSLog(#"started element : %#", elementName);
}
- (void) parser: (NSXMLParser*) parser didEndElement:(nonnull NSString *)elementName namespaceURI:(nullable NSString *)namespaceURI qualifiedName:(nullable NSString *)qName {
NSLog(#"ended element : %#", elementName);
}
- (void) parser: (NSXMLParser*) parser foundCharacters:(nonnull NSString *)string {
}
#end
main
int main(int argc, const char * argv[]) {
#autoreleasepool {
Parser* p = [[Parser alloc] initWithXMLData:#"<?xml version=\"1.0\" encoding=\"utf-8\"?><flash></flash><torch></torch>"];
}
return 0;
}

How to improve performance with NSXMLParser

i'm working with big xml file and need to download and parse him . inside 65k objects, but parsing is more then minute. I cannot understand how to optimize loading/parsing, please help me with advice. Also, because of long work cycle, need to big amount of memory and i don't know how to reduce memory consumption.
AFXMLRequestOperation *operation = [AFXMLRequestOperation
XMLParserRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, NSXMLParser *XMLParser) {
XMLParser.delegate = delegate;
[XMLParser parse];
if (delegate.done) {
NSLog(#"done");
}
} failure:nil];
[operation start];
- (void)parserDidStartDocument:(NSXMLParser *)parser {
_done = NO;
_items = [NSMutableArray new];
_isItem = NO;
_isPrice = NO;
_isDetail = NO;
}
// parsing Ended
- (void)parserDidEndDocument:(NSXMLParser *)parser {
_done = YES;
}
// if parsing error
-(void) parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
_done = YES;
_error = parseError;
}
// if validation error
-(void) parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError {
_done = YES;
_error = validationError;
}
// new element to parse
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:kItem]) {
// если да - создаем строку в которую запишем его значение
VZMenuItem *item = [[VZMenuItem alloc] init];
_item = item;
_item.name = attributeDict[#"name"];
_item.code = attributeDict[#"code"];
_isItem = YES;
return;
} else if ([elementName isEqualToString:kAttributes]) {
VZRecipe *recipe = [[VZRecipe alloc] init];
recipe.weight = [attributeDict[#"weight"] floatValue];
recipe.sugar = [attributeDict[#"sugar"] floatValue];
recipe.calories = [attributeDict[#"calories"] intValue];
recipe.milk = [attributeDict[#"milk"] floatValue];
recipe.eggs = [attributeDict[#"eggs"] unsignedIntValue];
_item.recipe = recipe;
return;
} else if ([elementName isEqualToString:kPrice]) {
_isPrice = YES;
return;
} else if ([elementName isEqualToString:kDetail]) {
_isDetail = YES;
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:kItem]) {
[_items addObject:_item];
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if(_isPrice) {
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
_item.price = [formatter numberFromString:string];
_isPrice = NO;
} else if(_isDetail) {
_item.detailUrl = string;
_isDetail = NO;
}
}
You should try parsing the XML file from a stream. You can initialise your NSXMLParser initWithStream: which takes a NSInputStream as argument, it will read and parse data in batches from the stream object.
You can create your NSInputStream with initWithURL: passing the URL from which to download the xml file. When you initialise the NSXMLParser with the stream it will automatically open and read the stream.
This will give you smaller responses more often over time using less memory and hopefully less CPU.
There's a slight hint to follow with this approach:
Apple says that NSXMLParser open the stream and starts reading, but by doing this even if you call:
[parser setDelegate:self] the delegate methods are not called if you don't call [parser parse]. The trick here is to call parse in a GCD block:
xmlParser = [[NSXMLParser alloc] initWithStream:inputStream]; [xmlParser setDelegate:self];
dispatch_block_t dispatch_block = ^(void) {
[xmlParser parse];
};
dispatch_queue_t dispatch_queue = dispatch_queue_create("parser.queue", NULL);
dispatch_async(dispatch_queue, dispatch_block);
dispatch_release(dispatch_queue);
Hope it helps.

Doesn't geting data in right form from a 3 level xml service when using NSXMLParser class

I have to parse a 3 level xml which showing below:-
<Navigation>
<parent>
<parentheader>
<![CDATA[ Home ]]>
</parentheader>
<url>my-profile</url>
<Content>...</Content>
</parent>
<parent>
<parentheader>
<![CDATA[ Exhibiton ]]>
</parentheader>
<child>
<childheader>
<![CDATA[ London Exhibition ]]>
</childheader>
<subchild>London Sub
<url>ezone</url>
<Content>...</Content>
</subchild>
</child>
<child>
<childheader>
<![CDATA[ Asia Exhibition ]]>
</childheader>
<url>exhibition-asia-tour</url>
<Content>...</Content>
</child>
</parent>
</Navigation>
i am implementing the NSXMLParser class and delegates method below is the code:-
.h File
#interface NavigationXMLParser : NSObject<NSXMLParserDelegate>
{
NSXMLParser *xmlParser;
NSMutableDictionary *item,*childDict,*subChildDict;
NSMutableArray *nodesArr,*childArr,*subChildArr;
NSMutableString *parent, *url,*child,*subchild;
NSString *currentElement;
BOOL childBool;
}
-(void) fetchXMLData;
#end
.m implementation file code:-
#implementation NavigationXMLParser
-(void) fetchXMLData
{
xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:[NSURL URLWithString:#"http://exhibitors.gastechkorea.com/admin/XMl_APP_Navigation.aspx"]];
[xmlParser setDelegate:self];
[xmlParser setShouldResolveExternalEntities:NO];
[xmlParser setShouldProcessNamespaces:NO];
[xmlParser setShouldReportNamespacePrefixes:NO];
[xmlParser parse];
}
- (void)parserDidStartDocument:(NSXMLParser *)parser
{
nodesArr =[[NSMutableArray alloc] init];
//[sharedSQLiteObj createFavoriteAgendaTableNamed:#"" withField1:#"" withField2:#"" withField3:#"" withField4:#""];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
NSString * errorString = [NSString stringWithFormat:#"Unable to download story feed from web site (Error code %i )", [parseError code]];
UIAlertView * errorAlert = [[UIAlertView alloc] initWithTitle:#"Error loading content" message:errorString delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qualifiedName attributes:(NSDictionary *)attributeDict
{
{
currentElement = [elementName copy];
if ([elementName isEqualToString:#"parent"])
{
item = [[NSMutableDictionary alloc] init];
parent = [[NSMutableString alloc]init];
url = [[NSMutableString alloc]init];
}
else if ([elementName isEqualToString:#"child"])
{
child = [[NSMutableString alloc]init];
childArr = [[NSMutableArray alloc] init];
childDict = [[NSMutableDictionary alloc] init];
url = [[NSMutableString alloc]init];
}
else if ([elementName isEqualToString:#"subchild"])
{
subchild = [[NSMutableString alloc]init];
subChildArr = [[NSMutableArray alloc] init];
subChildDict = [[NSMutableDictionary alloc] init];
url = [[NSMutableString alloc]init];
}
}
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([currentElement isEqualToString:#"parentheader"])
{
[parent appendString:string];
}
else if ([currentElement isEqualToString:#"url"])
{
[url appendString:string];
if (!(child.length ==0))
{
if (subchild.length==0)
{
[childDict setObject:string forKey:#"url"];
}
else{
[subChildDict setObject:string forKey:#"url"];
}
}
}
else if ([currentElement isEqualToString:#"childheader"])
{
[child appendString:string];
if (!(string.length ==0))
{
[childDict setObject:string forKey:#"childheader"];
}
}
else if ([currentElement isEqualToString:#"subchild"])
{
[subchild appendString:[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
if (!([string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]].length ==0))
{
[subChildDict setObject:string forKey:#"subchild"];
[subChildArr addObject:[subChildDict copy]];
[childDict setObject:subChildArr forKey:#"subchild"];
subChildDict = nil;
};
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:#"child"])
{
if (!(childDict.count ==0)) {
[childArr addObject:[childDict copy]];
childDict = nil;
}
}
if ([elementName isEqualToString:#"parent"])
{
[item setObject:[parent stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:#"parent"];
[item setObject:[url stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:#"url"];
if (!(childArr.count ==0))
{
[item setObject:childArr forKey:#"child"];
}
else
{
[item setObject:#"" forKey:#"child"];
}
//[item setObject:[subchild stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] forKey:#"subchild"];
[nodesArr addObject:[item copy]];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser
{
NSLog(#"nodesArr---%#",nodesArr);
}
#end
i got the responsed array from xmlparser class:-
(
{
child = "";
parent = Home;
url = "my-profile";
},
{
child = (
{
childheader = "\n";
}
);
parent = Exhibiton;
url = "exhibition-asia-tour";
},
{
child = (
{
childheader = "\n";
}
);
parent = Calender;
url = "http://www.google.com";
}
)
i am not getting the data in right structure i am wrong some where but didn't find the solution.
i want to get data in the below structure:--
(
{ parent="…."
child=""
url="……"
content="…."
}
{parent ="……"
child = ({ child="……";
subchild= ({
name= "….."
url="….."
content="….."
}
{
…………………….
…..……………..
})
}
{
child="……"
………………
})
)
}
Thanks in advace for your help!!!
it's all about how to make use of the NSXMLParserDelegate methods.
Your XML file can provide you the following informations:
The characters between [CDATA], and the characters between elements.
So you need to implement the following Delegate methods to retrive the informations from the XML file:
This method will get you every string between the [CDATA]:
-(void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock
{
NSMutableString *str=[[NSMutableString alloc]initWithData:CDATABlock encoding:NSUTF8StringEncoding];
[SomeArray addObject:str];
}
And this method will get you every string between elements:
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// here you need to alloc your string
NSMutableString *parent = [[NSMutableString alloc]init];
[parent appendString:string];
[parent release];
}
after you retrive your data in NSMutableArray and NSMutableString, you can filter your data as you need. But thats how to Parse your XML file.
It's just not that complicated. Good luck ^_^

Xml to dictionary parsing using XML reader [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.
I want to convert data in to dictionary ,any suggestions..
if you are newbie and don't know how to parse xml to dictionary... try with the below methods...
in .h file add this methods
#import <Foundation/Foundation.h>
#interface XMLReader : NSObject
{
NSMutableArray *dictionaryStack;
NSMutableString *textInProgress;
NSError **errorPointer;
}
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)errorPointer;
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)errorPointer;
#end
and in your .m file parse your URL using these methods.
NSString *const kXMLReaderTextNodeKey = #"text";
#interface XMLReader (Internal)
- (id)initWithError:(NSError **)error;
- (NSDictionary *)objectWithData:(NSData *)data;
#end
#implementation XMLReader
#pragma mark -
#pragma mark Public methods
+ (NSDictionary *)dictionaryForXMLData:(NSData *)data error:(NSError **)error
{
XMLReader *reader = [[XMLReader alloc] initWithError:error];
NSDictionary *rootDictionary = [reader objectWithData:data];
[reader release];
return rootDictionary;
}
+ (NSDictionary *)dictionaryForXMLString:(NSString *)string error:(NSError **)error
{
NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
return [XMLReader dictionaryForXMLData:data error:error];
}
#pragma mark -
#pragma mark Parsing
- (id)initWithError:(NSError **)error
{
if (self = [super init])
{
errorPointer = error;
}
return self;
}
- (void)dealloc
{
[dictionaryStack release];
[textInProgress release];
[super dealloc];
}
- (NSDictionary *)objectWithData:(NSData *)data
{
// Clear out any old data
[dictionaryStack release];
[textInProgress release];
dictionaryStack = [[NSMutableArray alloc] init];
textInProgress = [[NSMutableString alloc] init];
// Initialize the stack with a fresh dictionary
[dictionaryStack addObject:[NSMutableDictionary dictionary]];
// Parse the XML
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
parser.delegate = self;
BOOL success = [parser parse];
// Return the stack's root dictionary on success
if (success)
{
NSDictionary *resultDict = [dictionaryStack objectAtIndex:0];
return resultDict;
}
return nil;
}
#pragma mark -
#pragma mark NSXMLParserDelegate methods
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
// Get the dictionary for the current level in the stack
NSMutableDictionary *parentDict = [dictionaryStack lastObject];
// Create the child dictionary for the new element, and initilaize it with the attributes
NSMutableDictionary *childDict = [NSMutableDictionary dictionary];
[childDict addEntriesFromDictionary:attributeDict];
// If there's already an item for this key, it means we need to create an array
id existingValue = [parentDict objectForKey:elementName];
if (existingValue)
{
NSMutableArray *array = nil;
if ([existingValue isKindOfClass:[NSMutableArray class]])
{
// The array exists, so use it
array = (NSMutableArray *) existingValue;
}
else
{
// Create an array if it doesn't exist
array = [NSMutableArray array];
[array addObject:existingValue];
// Replace the child dictionary with an array of children dictionaries
[parentDict setObject:array forKey:elementName];
}
// Add the new child dictionary to the array
[array addObject:childDict];
}
else
{
// No existing value, so update the dictionary
[parentDict setObject:childDict forKey:elementName];
}
// Update the stack
[dictionaryStack addObject:childDict];
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
// Update the parent dict with text info
NSMutableDictionary *dictInProgress = [dictionaryStack lastObject];
// Set the text property
if ([textInProgress length] > 0)
{
[dictInProgress setObject:textInProgress forKey:kXMLReaderTextNodeKey];
// Reset the text
[textInProgress release];
textInProgress = [[NSMutableString alloc] init];
}
// Pop the current dict
[dictionaryStack removeLastObject];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
// Build the text value
[textInProgress appendString:string];
}
- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError
{
// Set the error pointer to the parser's error object
*errorPointer = parseError;
}
#end
I think this would be helpful to you for parsing the xml data.

nsmutablearray elements to nsstring

I want to retrieve elements that are parsed in a NSMutableArray and store them into a NSString variable and then store them in NSMutableArray as NSString (because I want to display the content in a NSComboBox). I tried this but it dosen't work. Can you fix the problem, I can't fix it:
//--this is the parsing code :
- (void)parser:(NSXMLParser *)parser
didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qualifiedName
attributes:(NSDictionary *)attributeDict {
if ([elementName isEqualToString:#"user"]) {
NSLog(#"user element found – create a new instance of User class...");
if(currentElementValue == nil)
currentElementValue = [NSMutableString string];
else
[currentElementValue setString:#""];
}
else {
currentElementValue = nil;
}
user = [[User alloc] init];
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string {
if (!currentElementValue) {
// init the ad hoc string with the value
currentElementValue = [[NSMutableString alloc] initWithString:string];
} else {
// append value to the ad hoc string
[currentElementValue appendString:string];
if (currentElementValue)
{
currentElementValue = nil;
}
}
NSLog(#"Processing value for : %#", string);
}
- (void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName {
if ([elementName isEqualToString:#"users"]) {
// We reached the end of the XML document
return;
NSLog(#"QUIT");
}
if ([elementName isEqualToString:#"userName"]) {
[[self user] setUserName:currentElementValue];
NSLog(#"final step for value: %#", user.userName);
NSLog(#"currentElementName content : %#", currentElementValue);
[currentElementValue release];
NSLog(#"release : %#", currentElementValue);
currentElementValue = nil;
NSLog(#"release : %#", currentElementValue);
}
if ([elementName isEqualToString:#"firstName"]) {
[[self user] setFirstName:currentElementValue];
[currentElementValue release];
currentElementValue = nil;
}
if ([elementName isEqualToString:#"lastName"]) {
[[self user] setLastName:currentElementValue];
[currentElementValue release];
currentElementValue = nil;
}
if ([elementName isEqualToString:#"user"]) {
NSLog(#"\n user=%# \n",user);
[users addObject:user];
NSLog(#"userName test : %#", users);
[user release];
user = nil;
}
}
-(BOOL)parseDocumentWithData:(NSData *)data {
if (data == nil)
return NO;
NSXMLParser *xmlparser = [[NSXMLParser alloc] initWithData:data];
[xmlparser setDelegate:self];
[xmlparser setShouldResolveExternalEntities:NO];
BOOL ok = [xmlparser parse];
if (ok == NO)
NSLog(#"error");
else
NSLog(#"OK");
[xmlparser release];
return ok;
}
// this is the xml file :
<users>
<user>
<userName>mspeller</userName>
<firstName>Mike</firstName>
<lastName>Speller</lastName>
</user>
<user>
<userName>mgdan</userName>
<firstName>Mila</firstName>
<lastName>Gdan</lastName>
</user>
</users>
//-------
NSMutableArray *tabletest= [[NSMutableArray alloc] init];
NSMutableString * result = [[NSMutableString alloc] init];
int i;
for(i=0; i < [users count]; i++){
[result appendString:[NSString stringWithFormat:#"%#",[[users objectAtIndex:i] valueForKey:#"userName"]] ];
NSLog(#"result==%#",result);
[tabletest addObject:result];
}
Based on your link in the comment section I think you're accessing the "userName" property the wrong way. You're trying to access it, as users contains NSDictionary objects. As far as I can see you're adding User objects to the NSMutableArray.
Try the following (I took the liberty to beautify the code a bit):
NSMutableArray *tabletest= [NSMutableArray array];
for (User* user in users)
{
NSString* result = [NSString stringWithFormat:#"%#", user.userName];
NSLog(#"result==%#",result);
[tabletest addObject:result];
}
Please correct me if I totally misunderstood your design.
I don't follow what your intention is, but what your code does at the moment is add the same string [user count] time to the array tabletest as follows:
The line:
[result appendString:[NSString stringWithFormat:#"%#",[[users objectAtIndex:i] valueForKey:#"userName"]] ];
accumulates into result the result of appending each [[users objectAtIndex:i] valueForKey:#"userName"] together - each iteration of the loop adds the next item to the end of result.
The line:
[tabletest addObject:result];
Adds the object referenced by result into the array. This is done once per iteration so the array ends up with [users count] references to the same object. Placing a reference to a mutable string into an array does not place a copy of its current value, just a reference to the string - mutate the string and the mutation is visible through the reference stored in the array.
So the final result of your code is an array of [users count] references to the same mutable string, and that string is the concatenation of all the [[users objectAtIndex:i] valueForKey:#"userName"] values.
What was your intent?
If you are trying to create an array of string representations of [[users objectAtIndex:i] valueForKey:#"userName"] then change the code to:
NSMutableArray *tabletest= [[NSMutableArray alloc] init];
for(int i = 0; i < [users count]; i++)
{
// create a string representation of userName
NSString *result = [NSString stringWithFormat:#"%#",[[users objectAtIndex:i] objectForKey:#"userName"]];
// add the string to the array
[tabletest addObject:result];
}
But maybe your intent is something else?