how to add NSString from loop in NSMutableArray - ios

I want to add NSString Name in NSmutableArray but I dont know about that.
I get 5 NSString name from url in wamp server and I want add these names in NSMutableArray.
this is my code but do not work!!! :
NSMutableArray *file;
for (int j=0; j < 5; j++) {
NSString *fileName = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name",j]]];
NSLog(#"%#",fileName);
[file addObject:fileName] //right???
}

You are not allocating NSMutableArray
NSMutableArray *file = [[NSMutableArray alloc] initWithCapacity:5];
If you are not sure about the number of elements gets added to array beforehand, you can use
NSMutableArray *file = [[NSMutableArray alloc] init];

Firstly, the NSMutableArray must be allocated.
Secondly, the using of magic numbers must be avoided.
Next, the readability of code should be improved by replace
NSString *fileName = [[NSString alloc]initWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name",j]]];
to something more convenient. Moreover, the memory here is allocated but never released.
Your code may be as follows:
const int numberOfFiles = 5;
NSMutableArray *file = [NSMutableArray array]
for(int i = 0; i < numberOfFiles; ++i){
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"http://192.168.1.101/janatan/filemanager.php?dir=root&file=%d&name", i]];
NSString *fileName = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
[file addObject:fileName];
}
But here are we can find some problems.
For example if url is changed on server-side you'd rewrite the code. If the number of elements is changed it's the same. So it would be good to find a way to avoid this kind of dependence.

Related

NSDictionary in NSMutableArray ios

I've a NSMutableArray array having NSDictionary keys as:
NSMutableArray *arr=#[#{#"A":#{#"user":#"obj1",#"friend":#"obj2"}}];
No I want to add objects to this NSMutableArray.
My Code:
for (int i = 0; i < 10; i++)
{
NSString *user = #"A"+i;
for(int i=0;i<50;i++) {
NSString *friend1 = #"B"+i;
NSString *friend2 = #"C"+i;
NSString *friend3 = #"D"+i;
}
}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:nil];
NSString *y= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",y);
Desired Output:
{"A":[{"user":"A1","friend":"B1"},{"user":"A1","friend":"B2"},{"user":"A2","friend":"B1"}]}
How can I set my objects in order to achieve desired output.
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", singleObjectTemplate];
Something like this. You can modify it as per your requirement to add multiple entries.
I hope this helps you in some way. Cheers!! :)
EDIT:
Suppose you want to add 3 objects to it.
NSString *str = #"";
for (int i = 0; i<3; i++)
{
NSString* singleObjectTemplate = [NSString stringWithFormat:#"{\"user\" : \"%#\",\"friend\" : \"%#\"}", user, friend];
str = [str stringByAppendingString:singleObjectTemplate];
if(i<2)
str = [str stringByAppendingString:#", "];
}
NSString* validJsonTemplate = [NSString stringWithFormat:#"{\"A\":[%#]}", str];

Potential leaks in iOS project

Hello i have this function, that gets dummy data from file in project:
Issues are shown in those lines:
NSString *path = [[NSBundle mainBundle] pathForResource: #"StatisticsDataJSON" ofType: #"TXT"]; - potential leak of an object.
NSMutableDictionary *statisticsResponse = [jsonParser objectWithString:data]; - potential leak of an object stored into 'jsonParser'
for (id key in statisticsResponse) { - potential leak of an object stored into 'statisticArray'
for (int i = 0; i < statsForDate.count; i++) { - potential leak of an object stored into 's'
if (self.statistics==nil)
{
self.statistics = [[NSMutableDictionary alloc]init];
NSString *path = [[NSBundle mainBundle] pathForResource: #"StatisticsDataJSON" ofType: #"TXT"];
NSError *error = nil;
NSString *data = [NSString stringWithContentsOfFile: path
encoding: NSUTF8StringEncoding
error: &error];
//NSLog(#"%#",data);
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *statisticsResponse = [jsonParser objectWithString:data];
for (id key in statisticsResponse) {
NSArray *statsForDate = [statisticsResponse objectForKey:key];
NSMutableArray *statisticArray = [[NSMutableArray alloc]init];
for (int i = 0; i < statsForDate.count; i++) {
Statistic *s = [[Statistic alloc]init];
s.locationId = [[statsForDate objectAtIndex:i] objectForKey:#"locationId"];
int value =[[[statsForDate objectAtIndex:i] objectForKey:#"visits"] integerValue];
s.visits = value;
value =[[[statsForDate objectAtIndex:i] objectForKey:#"totalUsers"] integerValue];
s.totalUsers = value;
value= [[[statsForDate objectAtIndex:i] objectForKey:#"uploads"] integerValue];
s.uploads = value;
value = [[[statsForDate objectAtIndex:i] objectForKey:#"downloads"] integerValue];
s.downloads = value;
value = [[[statsForDate objectAtIndex:i] objectForKey:#"apps"] integerValue];
s.apps = value;
[statisticArray addObject:s];
}
[self.statistics setObject:statisticArray forKey:key];
};
}
I have found that autorelease in ststisticsResponse - resolves the problem:
NSMutableDictionary *statisticsResponse = [[jsonParser objectWithString:data]autorelease];
But then something fails in SBJsonStreamParserAccumulator.m in dealoc function.
What is the problem?
Note that the warnings about potential leaks come on the line after the potential leak, because that's the first point at which the referenced object is technically "leaked". So your current fixes are probably over-releasing and causing crashes.
The first statement in your question actually refers to a leak in this line, immediately before:
self.statistics = [[NSMutableDictionary alloc]init];
You've got no further reference to that allocated dictionary, and it's a retained property, so you have a leak.
self.statistics = [[[NSMutableDictionary alloc]init] autorelease];
Will fix that one. The next one, you have to release the jsonParser when you've finished with it (after the parsing is done):
[jsonParser release];
I'm not going to go through all of them but you should get the idea. Basically you need to read the memory management guide, or update to ARC.
Pay attention to the variable names in the warnings. They tell you where the leak is.

Adding list of URLs to an array?

I'm using MHVideoPhotoGallery to create gallery's of images that are stored on my website. The current way to add images (as shown in the example on Github) is
MHGalleryItem *photo1 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
MHGalleryItem *photo2 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
MHGalleryItem *photo3 = [MHGalleryItem.alloc initWithURL:#"*ENTER IMAGE URL HERE*"
galleryType:MHGalleryTypeImage];
self.galleryDataSource = #[#[photo1,photo2,photo3]];
But I want to add hundreds of images and this is not the most ideal way to do it. What would be an easier way for me to accomplish this?
Thanks!
You have to start with a list of the URLs. What I would do is put this in a text file in my bundle. In code, when the app runs, I would open the text file (as an NSString) and split it into an NSArray. Now I've got an NSArray of the URLs. I would then cycle through the NSArray. So now we're inside a loop. For each item the array, I would initialize the MHGalleryItem and then add it to a previously created NSMutableArray with addObject:. Thus we have a two or three-line loop which is repeated, running through all the URLs.
The following is pseudo-code and untested (so it might contain errors), but it should give the general idea of the structure I'm suggesting:
NSMutableArray* temp = [NSMutableArray new];
NSString* s =
[NSString stringWithContentsOfFile:
[[NSBundle mainBundle] pathForResource:#"urls" ofType:#"txt"]
encoding:NSUTF8StringEncoding error:nil];
NSArray* urls = [s componentsSeparatedByString:#"\n"];
for (NSString* url in urls) {
MHGalleryItem *item = [[MHGalleryItem alloc] initWithURL:url
galleryType:MHGalleryTypeImage];
[temp addObject:item];
}
self.galleryDataSource = temp;
Loop. If you're putting numbers at the end of your variable names, you need a loop and/or an array.
NSMutableArray * photos = [NSMutableArray new];
NSArray * photoPaths = [NSArray arrayWithContentsOfFile:plistContainingPhotoPaths];
for( NSString * path in photoPaths ){
NSURL * photoURL = [NSURL URLWithString:path];
MHGalleryItem * photo = [[MHGalleryItem alloc] initWithURL:photoURL
galleryType:MHGalleryTypeImage];
[photos addObject:photo];
}
And don't use dot syntax for alloc, or your code will burst into flames.
Use a naming protocol on your website such as:
www.mywebsite.com/appImageGallery/insertImageNumber
And replace the insertImageNumber with the number of you image. Then add this for loop to get all of the images and add them to the array.
NSMutableArray *mutableGalleryDataSource = [self.galleryDataSource mutableCopy]
for(int i = 0; i < numberOfImagesOnWebsite; i++){ //replace numberOfImagesOnWebsite with the number of images on your website.
MHGalleryItem *newItem = [MHGalleryItem.alloc initWithURL:[#"www.mywebsite.com/appImageGallery/" stringByAppendingString:[NSString stringWithFormat: #"%i", i]] galleryType:MHGalleryTypeImage];
[mutableGalleryDataSource addObject:newItem];
}
self.galleryDataSource = mutableGalleryDataSource;
There is also an -addObjectsFromArray method on NSMutableArray.

Objective-C Download PLIST and use within table

I'm fairly new to Objective-C programming. I'm trying to build an app for personal use to view event info which is contained on my web server. I wish for each Event Title string to be shown as a separate row within my UITableView.
I'm using CFPropertyList to create the plist from MySQL. Here's what my plist looks like:
I'm downloading the plist like so:
NSString *stringURL = #"http://www.example.com/events.plist";
NSURL *url = [NSURL URLWithString:stringURL];
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory,#"events.plist"];
[urlData writeToFile:filePath atomically:YES];
}
Then this is how I'm trying to load the info into their arrays:
events = [[NSDictionary alloc] initWithContentsOfFile:filePath];
ID = [events objectForKey:#"Event ID"];
title = [events objectForKey:#"Event Title"];
date = [events objectForKey:#"Event Date"];
price = [events objectForKey:#"Price"];
totalTickets = [events objectForKey:#"Total Tickets"];
ticketsSold = [events objectForKey:#"Tickets Sold"];
ticketsRemaining = [events objectForKey:#"Tickets Remaining"];
postStatus = [events objectForKey:#"Post Status"];
postContent = [events objectForKey:#"Post Content"];
Now here's where I'm having trouble. Now when I'm debugging the number of rows the 'events' dictionary has it returns 0.
Therefore I cannot set the 'numberOfRowsInSection'. Nor does [title objectAtIndex:indexPath.row] work.
I believe the issue lays with how I'm setting up the NSDictionary, but due to my lack of Objective-C and array knowledge, I'm unable to overcome this issue.
Here's your problem:
events = [[NSDictionary alloc] initWithContentsOfFile:filePath];
Your plist is an array of dictionaries and you're trying to load that array as a dictionary. Try this instead:
events = [NSArray arrayWithContentsOfFile:filePath];
Edit: To extract the titles into an array so you can use them in table cells, do this:
NSMutableArray *titles = [NSMutableArray array];
for (NSDictionary *event in events) {
NSString *title = [event objectForKey:#"Event Title"];
[titles addObject:title];
}

csv to core data method error 2012

I have read a few posts and found a method. I adapted it to my app, however at [self saveContext]; I get a bad instruction error.
Please let me know why, and if this method makes sense. Also I am using \r because in the csv each item is in its own row.
Thank you in advance
-(void)addData{
NSString *paths = [[NSBundle mainBundle] resourcePath];
NSString *bundlePath = [paths stringByAppendingPathComponent:#"coredatainfo.csv"];
NSString *dataFile = [[NSString alloc] initWithContentsOfFile:bundlePath];
NSArray *dataRows = [dataFile componentsSeparatedByString:#"\r"];
[dataFile release];
FirstCDitem *myItem;
for (int i = 0 ; i < [dataRows count] ; i++)
{
NSArray *dataElements = [[dataRows objectAtIndex:i] componentsSeparatedByString:#","];
NSLog(#"Added: %d %#",i,dataElements);
myItem = (FirstCDitem *)[NSEntityDescription insertNewObjectForEntityForName:#"FirstCDitem" inManagedObjectContext:[self managedObjectContext]];
[FirstCDitem setTitle:[dataElements objectAtIndex:i]];
[self saveContext];
}
}
There are two problems in this code line:
[FirstCDitem setTitle:[dataElements objectAtIndex:i]];
i is the current row number, so it probably makes no sense to use it as index to the dataElements array. Perhaps you want the first element in the row?
setTitle must sent to the instance myItem, not to the class FirstCDItem.
So the line should look like this:
[myItem setTitle:[dataElements objectAtIndex:0]];

Resources