Convert NSString to NSMutableArray to added in tableview - objective-c

Hi I wanted convert NSString into NSMutable array and in the final added into Tableview my String is this
result=Vlad,Mama,Papa,Son
I wanted to do something this
Anarray=(Vlad,Mama,Papa,Son)
And added to Tableview. Can anathing help me.What I do
NSArray *arr = [result componentsSeparatedByString:#","];
dataArray=[[NSArray alloc]initWithObjects:arr ,nil];
And try to added into
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString*cellid=#"Cell";
UITableViewCell*cell=[tableView dequeueReusableCellWithIdentifier:cellid];
if(cell==Nil){
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellid];
}
cell.textLabel.text=[dataArray objectAtIndex:indexPath.row];
return cell;
}
But I have mistake
enter image description here

componentsSeparatedByString returns you the array, if you want a mutable array you can use the following code.
NSArray *arrComponents = [str componentsSeparatedByString:#","];
NSMutableArray *arrmFilter = [[NSMutableArray alloc] init];
for(int i = 0; i < [arrComponents count] ;i++)
{
NSString *str = [arrComponents objectAtIndex:i];
[arrmFilter addObject:str];
}

you've added your "arr" as element inside your "dataArray".
in case dataArray is NSMutableArray :
dataArray = [NSMutableArray arrayWithArray:arr];
in case dataArray is NSArray :
datatArray = [NSArray arrayWithArray:arr];

May be you didn't alloc and init dataArray.
You can try below code.
#import "ViewController.h"
#import "MyTableViewCell.h"
#interface ViewController ()
#end
#implementation ViewController
{
NSMutableArray *arrData;
}
- (void)viewDidLoad {
[super viewDidLoad];
NSString *str = #"objective c,swift,java";
arrData = [[NSMutableArray alloc]initWithArray:[str componentsSeparatedByString:#","]];
NSLog(#"%#",arrData);
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return arrData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath];
cell.lblData.text = [arrData objectAtIndex:indexPath.row];
return cell;
}

componentsSeparatedByString gives you an array. Which is what you want.
[[NSArray alloc]initWithObjects:arr ,nil] gives you an array containing just one element, an array containing your strings. Which is totally wrong. An array containing four strings is absolutely not the same as an array containing an array containing four strings.
dataArray.count will be 1 - because there is one element which is itself an array. And dataArray [0] will be that array, not a string.

Related

Objective-C array issues

I have this NSArray and each item returns a POIndex and PONumber and I am putting each item of the array inside another Array and the other array is returning like this:
POIndex
PONumber
POIndex
PONumber
Here is my code:
- (void)GetRequest
{
NSArray *tableData = [dataSource.areaData GetPurchaseOrderItems:[NSString stringWithFormat:#"%#%#",areaPickerSelectionString,unitPickerSelectionString]];
if(!self.objects){
self.objects = [[NSMutableArray alloc]init];
}
for(int i = 0; i < [tableData count]; i++){
[self.objects addObjectsFromArray:[tableData objectAtIndex:i]];
}
[self.tableView reloadData];
}
Here is a screenshot of what tableData is returning:
What I am looking to do is have have the PONumber as the key and POIndex as the display value, how would I do this?
I have tried the following:
NSMutableDictionary *subDict=[[NSMutableDictionary alloc]init];
for (NSDictionary *dict in tableData) {
[subDict setValue:[dict objectForKey:#"POIndex"] forKey:[dict objectForKey:#"PONumber"]];
[self.objects addObject:subDict];
}
but this displays like so:
{
{
{
{
Here is what is displaying it:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *object = self.objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
Your tableData array contains NSDictionary at each index. So you can use the same array in your cellForRowIndexPath method like as follows,
#property(nonatomic, retain) NSArray * tableData;
- (void)GetRequest
{
self.tableData = [dataSource.areaData GetPurchaseOrderItems:[NSString stringWithFormat:#"%#%#",areaPickerSelectionString,unitPickerSelectionString]];
[self.yourTableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *strPOIndex = [self.tableData[indexPath.row] valueForKey:#"POIndex"];
cell.textLabel.text = strPOIndex;
return cell;
}

Error while passing data from a tableview to a detail tableview

I'm going to become a little crazy for this solution..
I have a TableView with his list of item (an Array from csv Parsing), I need to pass some data from this Array to the list of a Detail TableView when I select a cell..
I reed a bit of solutions and I tried them, but this should be the best solution and the code is conform to the guides.. But when I select a cell I have an "EXC_BAD_ACCESS" but I can't understand where is the zombie object, so I post all class:
#import "inRaggioViewController.h"
#import "iR-DetailViewController.h"
#implementation inRaggioViewController
#synthesize lista, record;
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *listaNonOrdinata = [[NSMutableArray alloc]init];
self.navigationItem.title = #"Tipologia";
NSString *fileString = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"Lista1" ofType:#"csv"] encoding:NSUTF8StringEncoding error:nil];
record = [fileString csvRows];
dettaglio = [[NSMutableArray alloc]init];
id doppio = nil;
for (int i=1; i < record.count; i++) {
for (int j=0; j < listaNonOrdinata.count; j++) {
doppio = [[record objectAtIndex:i] firstObjectCommonWithArray:listaNonOrdinata];
if (doppio == nil) {
// [dettaglio addObject:[NSNumber numberWithBool:NO]];
} else {
// [dettaglio addObject:[NSNumber numberWithBool:YES]];
}
}
if (doppio == nil) {
[listaNonOrdinata addObject:[[record objectAtIndex:i]objectAtIndex:0]];
}
}
//Ordino array in ordine alfabetico
lista = [[NSArray alloc]init];
lista = [listaNonOrdinata sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)];
[listaNonOrdinata release];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return lista.count;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
NSString *cellValue = [lista objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;
// NSLog(#"dettaglio bool Value: %s",[[dettaglio objectAtIndex:indexPath.row]boolValue] ? #"YES" : #"NO");
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// Navigation logic may go here. Create and push another view controller.
NSLog(#"Selezionata riga %i",indexPath.row+1);
iR_DetailViewController *detailViewController = [[iR_DetailViewController alloc]init];
// ...
// Pass the selected object to the new view controller.
detailViewController.navigationItem.title = [self.lista objectAtIndex:indexPath.row];
[detailViewController.lista addObject:[[self.record objectAtIndex:indexPath.row+1]objectAtIndex:1]];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc. that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[dettaglio release];
[record release];
[lista release];
[super dealloc];
}
#end
The strange thing is that list object work fine in the other methods, only in the selection method it gives problem...
Sorry for my bad english, I don't speak english well. Thanks at all for advice!
I'VE RESOLVED!
Thanks to all, the problem was that I must retain list and record objects at the end of viewDidLoad!
If the list you're trying to add to is an NSArray it will not work. You can only add to it if it is an NSMutableArray. Try that?

Displaying data retrieved from Parse in UITableView

After all progress i made with your answers, my issue changed. So i am changing my question with clearer way. I have an UITableView which is showing my retrieved data from Parse.com. So i made a NSMutableArray for adding objects to that array when they are retrieved. But my problem is even i add objects to NSMutableArray, my table does not show anything but default screen of UITableView. I thing the issue is UITableView is formed before my NSMutableArray got its objects. Here is my code:
Note: The PropertyClass is the class which has the properties of my objects.
At MyTableViewController.h
#interface MyTableViewController : UITableViewController <CLLocationManagerDelegate> {
PFObject *object;
}
#property (strong, nonatomic) IBOutlet UITableView *MyTableView;
#end
At UITableViewController.m
#interface MyTableViewController ()
#property(strong)NSMutableArray *myNSMutableArray;
#end
#implementation MyTableViewController
#synthesize myNSMutableArray,MyTableView;
-(void) retrievingDataFromParse{
PFQuery *query = [PFQuery queryWithClassName:#"MyObjectsClass"];
[query whereKey:#"ObjectsNumber" lessThanOrEqualTo:10];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d scores.", objects.count);
if (objects.count==0) {
NSString *objectError = #"There no object retrieved from Parse";
PropertiesClass *PC = [[PropertiesClass alloc]initWithPropert1:objectError Propert2:nil Propert3:nil Propert4:nil];
[myNSMutableArray addObject:PC];
}
for (int i = 0; i < objects.count; i++) {
object = [objects objectAtIndex:i];
NSString *Propert1 = [object objectForKey:#"Propert1"];
NSNumber *Propert2 = [object objectForKey:#"Propert2"];
NSNumber *Propert3 = [object objectForKey:#"Propert3"];
NSString *Propert4 = [object objectForKey:#"Propert4"];
PropertiesClass *PC = [[PropertiesClass alloc]initWithPropert1:Propert1 Propert2:Propert2 Propert3:Propert3 Propert4:Propert4];
[myNSMutableArray addObject:PC];
};
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.myNSMutableArray = [NSMutableArray array];
[self retrievingDataFromParse];
[MyTableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [myNSMutableArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PropertiesClass *PC= [myNSMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text=PC.Propert1;
return cell;
}
Looking at your code i see that you never create a UITableViewCell, you should change this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
PropertyClass *PC = [myMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = PC.x;
return cell;
}
with this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (nil == cell){
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
PropertyClass *PC = [myMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = PC.x;
return cell;
}
the method dequeueReusableCellWithIdentifier:forIndexPath: return a UITableViewCell only if there are unused, but already allocated, cells in your table view. otherwise it returns nil.
Also when you update the mutable array containing all your data you should call [yourTableView reloadData] to force the table view to reload its content.
Your code is quite cryptic. Few suggestions here.
First, rename variables and methods with camelCaseNotation (camel case notation). For example, MyMutableArray should be myMutableArray. RetrievingDataFromParse should be retrievingDataFromParse (and so on). Start upper case letter are for classes.
Second, what does this code mean (I put comment on your code)?
for (int i = 0; i < objects.count; i++) {
// where do you have defined object?
object = [objects objectAtIndex:i];
NSString *x = [object objectForKey:#"x"];
NSNumber *y = [object objectForKey:#"y"];
NSNumber *z = [object objectForKey:#"z"];
NSString *t = [object objectForKey:#"t"];
// is Mekan a subclass of PropertiyClass or what else?
PropertiyClass *Properties = [[Mekan alloc]initWithx:x y:y z:z t:t]
// what's MekanKalibi? Maybe you need to add Properties
[MyMutableArray addObject:MekanKalibi];
}
Edit
If you don't use iOS6 - (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier you should alloc-init cells.
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell) {
// alloc-init a new cell here...
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
// or if you don't use ARC
// cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
PropertyClass *PC = [myMutableArray objectAtIndex:indexPath.row];
cell.textLabel.text = PC.x;
return cell;
Edit 2
I don't know how parse works but I suppose it manages async requests. So, at the end of your for loop, just call reload data in the table.
Parse states:
The InBackground methods are asynchronous, so any code after this will run immediately. Any code that depends on the query result should be moved inside the completion block above.
I had the same problem. When you reload the table, you need to move it so it is inside the block. Worked for me.
I'm not 100% sure how the asynchronous parts affect it so. I know that the start of my viewDidload and the end occured then this block, hence the problem.
People should probably up this as this solves the issue.
Cheers.
All you have to do is reload tableView in the block... this will show data.
for (int i = 0; i < objects.count; i++) {
object = [objects objectAtIndex:i];
NSString *Propert1 = [object objectForKey:#"Propert1"];
NSNumber *Propert2 = [object objectForKey:#"Propert2"];
NSNumber *Propert3 = [object objectForKey:#"Propert3"];
NSString *Propert4 = [object objectForKey:#"Propert4"];
PropertiesClass *PC = [[PropertiesClass alloc]initWithPropert1:Propert1 Propert2:Propert2 Propert3:Propert3 Propert4:Propert4];
[myNSMutableArray addObject:PC];
};
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
**[MyTableView reloadData];**
}];

NSMutableArray not showing in UITableView

In my header file:
#interface HTMLClassesViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
So I did declare the dataSource and delegate.
In my implementation file:
- (void)viewDidLoad {
[super viewDidLoad];
if (self.arrayOfClasses == nil) {
self.arrayOfClasses = [[NSMutableArray alloc] init];
}
NSMutableArray *array = [[NSMutableArray alloc] init];
... // Gather data from HTML source and parse it into "array"
self.arrayOfClasses = array; //arrayOfClasses here is non-nil (with correct objects)
NSLog(#"%# test1", [self.arrayOfClasses objectAtIndex:0]);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
NSLog(#"%# test1.5", [self.arrayOfClasses objectAtIndex:0]);
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSLog(#"%# test2", [self.arrayOfClasses objectAtIndex:0]);
return [self.arrayOfClasses count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"%# test3", [self.arrayOfClasses objectAtIndex:0]);
static NSString *CellIdentifier = #"WebCollegeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text = [self.arrayOfClasses objectAtIndex:indexPath.row];
return cell;
}
And this is the output from NSLog:
2012-11-24 22:52:19.125 ArizonaCollegeSearch[72404:c07] CSE 240 test1
2012-11-24 22:52:19.126 ArizonaCollegeSearch[72404:c07] CSE 240 test1.5
2012-11-24 22:52:19.127 ArizonaCollegeSearch[72404:c07] (null) test1.5
2012-11-24 22:52:19.127 ArizonaCollegeSearch[72404:c07] (null) test2
As you can see, numberOfSectionsInTableView is being called with an non-null object, and then with a null object, and numberOfRowsInSection is being called with a null object, and cellForRowAtIndexPath is not being called at all. I don't even have a [self.tableView reloadData] anywhere.
Any suggestions?
So the property holding your array needs to be declared strong, else it will get deallocated when the variable it has been assigned to is deallocated. And in the case of a local variable (your NSMutableArray *array), that's the end of its scope, e.g. when the function viewDidLoad returns.

NSArray elements which have from NSSet not displayed in TableViewCell

I have NSArray elements which is implemented from NSSet and if i tried to display the elements in Table View Cell i'm getting BAD ACCESS issue at tableView numberOfRowsInSection part.Here is my code
- (void)viewDidLoad
{
[super viewDidLoad];
jsonurl=[NSURL URLWithString:#"http://www.sample.net/products.php"];//NSURL
jsondata=[[NSString alloc]initWithContentsOfURL:jsonurl];//NSString
jsonarray=[[NSMutableArray alloc]init];//NSMutableArray
self.jsonarray=[jsondata JSONValue];
array=[jsonarray valueForKey:#"post_title"];
set = [NSSet setWithArray:array];//NSMutableSet
array=[set allObjects];//NSArray
NSLog(#"%#",array);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [array count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{ cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell...
cell.textLabel.text = [self.array objectAtIndex: [indexPath row]];
return cell;
}
Kindly help please.Thanks in advance.
In your code you are not allocating the array. You are setting an autoreleased object to that array that's why you are getting this error.
Replace array=[set allObjects]; with array=[[set allObjects] retain];
I think this is because you are setting your instance variables to autoreleased objects without retaining them.
Either make "set" and "array" retained properties and do
self.set = [NSSet setWithArray:self.array];
// This is already a bit weird... If the set is made from the array, the array will be unchanged.
self.array = [self.set allObjects];
Or just retain them:
set = [[NSSet setWithArray:array] retain];
etc.
Since setWithArray and allObjects return autoreleased objects, you are left with dangling pointers as soon as you leave the scope of viewDidLoad.