How to assign NSArray data to NSMutableArray in iphone? - iphone

In my application I have an NSArray which contains some data. I want to take that data and put it into an NSMutableArray called subArrayData. I am able to insert the data from my first array into the mutable array, but when the application runs I am getting:
warning:Incompatible pointer types assigning to 'nsmutablearray *'
from 'nsarray *' please help out.
following is my code:
.h file
#import <UIKit/UIKit.h>
#interface AddNew : UIViewController
{
NSMutableArray *subArrayData;;
}
#property(nonatomic ,retain)NSMutableArray *subArrayData;
.m file
#import "AddNew.h"
#import "DashBoardPage.h"
#import "SubmitYourListing.h"
#implementation AddNew
#synthesize subArrayData;
-(void)accommodationAndTravel
{
subArrayData =[[NSArray alloc] initWithArray:[NSArray arrayWithObjects:#"Select one",#"Accommodation and travel hospitality",#"Apartments and villas",#"Bed and Breakfast",#"Caravan parks and campsites",#"Hospitality",
#"Hotels and Motels",#"Snow and Ski lodges",#"Tourist attractions and tourism information",#"Tours and Holidays",#"Travel agents and Services",nil]];
}

You can convert any NSArray to an NSMutable array by calling its -mutableCopy method:
NSArray *someArray = ...;
NSMutableArray* subArrayData = [someArray mutableCopy];

change the .m file
#import "AddNew.h"
#import "DashBoardPage.h"
#import "SubmitYourListing.h"
#implementation AddNew
#synthesize subArrayData;
-(void)accommodationAndTravel
{
subArrayData =[[NSMutableArray alloc] initWithArray:[NSArray arrayWithObjects:#"Select one",#"Accommodation and travel hospitality",#"Apartments and villas",#"Bed and Breakfast",#"Caravan parks and campsites",#"Hospitality",
#"Hotels and Motels",#"Snow and Ski lodges",#"Tourist attractions and tourism information",#"Tours and Holidays",#"Travel agents and Services",nil]];
}

Just call one of NSMutableArray's initializers, like so:
subArrayData = [[NSMutableArray alloc] initWithObjects:
#"Select one",
#"Accommodation and travel hospitality",
#"Apartments and villas",
#"Bed and Breakfast",
#"Caravan parks and campsites",
#"Hospitality",
#"Hotels and Motels",
#"Snow and Ski lodges",
#"Tourist attractions and tourism information",
#"Tours and Holidays",
#"Travel agents and Services",
nil]];
For the cases when you are dealing with an existing NSArray, you can make a mutableCopy:
- (id)initWithArray:(NSArray *)array
{
self = [super init];
if (nil != self) {
subArrayData = [array mutableCopy];
...

Related

Iphone Contact list. Sort TableView view alphabetically

Im making a IPHONE Phonebook app that has an array of contacts(objects). I am trying to sort this array so it displays the lastName in alphabetical order
But nothing seems to work. I'm not sure where i would put my code in the "MasterViewController". HERE IS PART OF MY CODE
My object looks like the following.
#interface PhoneBookEntry : Person
#property NSString *firstName;
#property NSString *lastName;
#property NSString *address;
#property NSString *phoneNumber;
#end
#interface MasterViewController : UITableViewController
#property NSMutableArray *elements;
#end
#implementation MasterViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.elements = [[NSMutableArray alloc] init];
}
Assume that the array already has elements in it.
I need to sort the "self.elements.lastName" array alphabetically
PLEASE HELP!!!!!!!!
[self.elements sortUsingDescriptors:#[[NSSortDescriptor sortDescriptorWithKey:#"lastName" ascending:YES]]];

objective c how to create dictionaries dynamically and refer to them

i need to create and destroy dynamically dictionaries, or arrays,
and have them as instance variables,
so for example, [pseudocode]
*.h
nsmutableDictionary myDictn???
nsstring arrayn ???
how to create an instance dictionarie, and property, that dinamically get created and destroyed?, and how to refer to it?
*.m
n = 0
create container {
myDictn alloc init
n+1
}
other {
myDictn addobject#"data" forKey"myKey"
}
destroy container {
myDictn release
n-1
}
So what intend to show is that i would like to have myDict1, myDict2...
if created,
or destroy them if needed
thanks a lot!
To create dictionaries dynamically & add entries to them you could do this -
NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] retain];
[dictResult setValue:result forKey:#"key"];
Here result can be anything. NSString or NSArray etc. Also using retain retains this object & causes a memory leak if not explicitly released. Instead try to do autorelease that way ios takes care of releasing the object when its no longer referred to. You do that like so -
NSMutableDictionary *dictResult = [[[NSMutableDictionary alloc] init] autorelease];
This is all you need to create dictionaries dynamically.
I think what you're asking for is how to have multiple mutable dictionaries dynamically created. You haven't said where the numbering scheme is coming from, so you may need to modify this solution for your purposes.
What you want is an array or dictionary of dictionaries.
Make one NSMutableDictionary called something like dictionaryContainer. Then, when you want to create dictionary number 7, do
NSMutableDictionary *aDictionary = [NSMutableDictionary new];
[dictionaryContainer setObject:aDictionary forKey:[NSNumber numberWithInt:7]];
To recall that dictionary, do
NSMutableDictionary *theSameDictionary = [dictionaryContainer objectForKey:[NSNumber numberWithInt:7]];
You don't have to hard code the 7, you can get it from anywhere and pass it in as an integer variable.
If I got your question correctly, this is pretty easy
#interface MyClass {
NSMutableDictionary *dict;
NSMutableArray *arr;
}
#property (nonatomic, retain) NSMutableDictionary *dict;
#property (nonatomic, retain) NSMutableArray *arr;
#end
Implementation file
#import "MyClass.h"
#implementation MyClass
#synthesize dict;
#synthesize arr;
- (id) init {
self = [super init];
if (self) {
dict = [[NSMutableDictionary alloc] init];
arr = [[NSMutableArray alloc] init];
}
return self;
}
- (void) dealloc {
[dict release];
[arr release];
[super dealloc];
}
- (void) otherStuff {
[dict setObject: #"value" forKey: #"key"];
[arr addObject: #"item"];
}
#end
usage from another class:
...
MyClass *instance = [MyClass new];
[instance.dict setObject: #"value" forKey: #"key"];
NSLog(#"Array items: %#", instance.arr);
[instance release];
...

Sorting NSDictionary with multiple constraints

I have a NSDictionary collection whose key is a unique id and value is an array with two different objects (FruitClass, ProductClass) and I would like to group the collection such that it's sorted first by ProductClass.productName and then by FruitClass.itemName.
So the final list would look something like:
{apple, butter}
{apple, pie}
{banana, daiquiri}
{banana, smoothie}
{melon, zinger}
where the first item is a FruitClass instance item and second is a ProductClass instance item.
What's the best way to go about doing this? Most of the examples I've come across are done on one key. How do you do it with an NSDictionary that has 2 different object types?
Looking at NSDictionary's's keysSortedByValueUsingSelector,
- (NSArray *)keysSortedByValueUsingSelector:(SEL)comparator
I get the impression that you would create the 'compare' method on the class type of the value object. So for multiple field sort, would I have to resort to creating a new object type, 'CombinedClass' which contains FruitClass & ProductClass and implement a 'compare' to make this happen?
FruitClass:
{
NSString *itemName;
}
#end
#interface ProductClass
{
NSString *productName;
}
#end
If there is a data structure that consists of only one fruit and only one product then an array is not really a good option. You can use another class and provide a compare: comparator:
#interface ComboClass : NSObject
{
FruitClass *fruit;
ProductClass *product;
}
#property(nonatomic,retain) FruitClass *fruit;
#property(nonatomic,retain) ProductClass *product;
- initWithFruit:(FruitClass *)f andProduct:(ProductClass *) p;
#end
#implementation ComboClass
#synthesize fruit;
#synthesize product;
- (void) dealloc
{
[fruit release];
[product release];
[super dealloc];
}
- initWithFruit:(FruitClass *)f andProduct:(ProductClass *) p
{
self = [super init];
if (!self) return nil;
self.fruit = f; // some recommend against accessor usage in -init methods
self.product = p;
return self;
}
- (NSComparisonResult) compare:(id) another
{
NSComparisonResult result = [self.fruit.itemName compare:another.fruit.itemName];
if (result == NSOrderedSame)
return [self.product.productName compare:another.product.productName];
else
return result;
}
#end
Alternatively, you might be able to use an NSDictionary with product and fruit key-value pairs, (so you'll end up with dictionaries inside a dictionary). The NSSortDescriptor class can be used to sort arrays using values of key-paths, so it might be another option to explore.
You could add a category to NSArray that would do the comparison and you wouldn't have to create another class.
#interface NSArray ( MySortCategory )
- (NSComparisonResult)customCompareToArray:(NSArray *)arrayToCompare;
#end
The implementation should be pretty straightforward based on your description.
Edit I got a little miffed that this was marked down with no comment, so I did a full implementation to make sure it would work. This is a little different than your sample, but the same idea.
FruitsAndProducts.h
#interface Fruit : NSObject
{
NSString *itemName;
}
#property(nonatomic, copy)NSString *itemName;
#end
#interface Product : NSObject
{
NSString *productName;
}
#property(nonatomic, copy)NSString *productName;
#end
FruitsAndProducts.m
#import "FruitsAndProducts.h"
#implementation Fruit
#synthesize itemName;
#end
#implementation Product
#synthesize productName;
#end
NSArray+MyCustomSort.h
#interface NSArray (MyCustomSort)
- (NSComparisonResult)customCompareToArray:(NSArray *)arrayToCompare;
#end
NSArray+MyCustomSort.m
#import "NSArray+MyCustomSort.h"
#import "FruitsAndProducts.h"
#implementation NSArray (MyCustomSort)
- (NSComparisonResult)customCompareToArray:(NSArray *)arrayToCompare
{
// This sorts by product first, then fruit.
Product *myProduct = [self objectAtIndex:0];
Product *productToCompare = [arrayToCompare objectAtIndex:0];
NSComparisonResult result = [myProduct.productName caseInsensitiveCompare:productToCompare.productName];
if (result != NSOrderedSame) {
return result;
}
Fruit *myFruit = [self objectAtIndex:1];
Fruit *fruitToCompare = [arrayToCompare objectAtIndex:1];
return [myFruit.itemName caseInsensitiveCompare:fruitToCompare.itemName];
}
#end
Here it is in action
// Create some fruit.
Fruit *apple = [[[Fruit alloc] init] autorelease];
apple.itemName = #"apple";
Fruit *banana = [[[Fruit alloc] init] autorelease];
banana.itemName = #"banana";
Fruit *melon = [[[Fruit alloc] init] autorelease];
melon.itemName = #"melon";
// Create some products
Product *butter = [[[Product alloc] init] autorelease];
butter.productName = #"butter";
Product *pie = [[[Product alloc] init] autorelease];
pie.productName = #"pie";
Product *zinger = [[[Product alloc] init] autorelease];
zinger.productName = #"zinger";
// create the dictionary. The array has the product first, then the fruit.
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObjects:zinger, banana, nil], #"zinger banana", [NSArray arrayWithObjects:butter, apple, nil], #"butter apple", [NSArray arrayWithObjects:pie, melon, nil], #"pie melon", nil];
NSArray *sortedKeys = [myDict keysSortedByValueUsingSelector:#selector(customCompareToArray:)];
for (id key in sortedKeys) {
NSLog(#"key: %#", key);
}
Your comparator can work on whatever you throw at it... you can make it treat its two arguments as NSArray objects, if this is what you need. When you put arrays as values into your dictionary, then just use those - no need for another class.
If you want to build a new class anyway (maybe for design reasons) - go for it, but it is not a "must do" here.
Edit: strike out to make clear that only one argument is given - as the other one is the object the selector is called on. Using NSArray will need a class extension, a custom class is much cleaner.

Error When adding Object to NSMutableArray

I am getting errors when trying to add items to a NSMutableArray which is encapsulated within an object.
Code follows:
#import <Foundation/Foundation.h>
#interface TestObject : NSObject {
NSMutableArray *myArray;
}
#property (nonatomic, retain) NSMutableArray *myArray;
#end
#import "TestObject.h"
#implementation TestObject
#synthesize myArray;
- (id) init {
if(self= [super init]){
// Initialise the Mutable Array
myArray = [[NSMutableArray alloc] init];
}
return self;
}
- (void) dealloc {
[super dealloc];
[myArray release];
}
#end
Calling:
TestObject *testObject = [[TestObject alloc] init];
NSString *someString = #"blah blah blah";
NSLog(#"%#", someString);
[testObject.myArray addObject:someString];
NSLog(#"Test Object Array Count: %#", [testObject.myArray count]);
[testObject release];
Can anyone tell me why this throws an error when calling count?
I have also tried the copy the Mutable Array to a local variable and get the same result when calling count on the local variable.
Warning warning warning!!!
[super dealloc] is the last thing you should do in your -dealloc method, not the first!
It's a good thing it just showed a warning, when I have done the same it has crashed.
The reason is that %# is an object placeholder. But the count method returns NSInteger which is a primitive datatype and the placeholder for it is %d, as you have correctly noted in the comment.

As for iPhone Application Development, it is a question

I am developing iPhone Application.
MyApplicationData.h
#import <Foundation/Foundation.h>
#interface MyApplicationData : NSObject {
NSMutableArray* appData;
}
#property (retain) NSMutableArray* appData;
-(void)loadData;
-(void)addAppDataItemPrice:(NSString*)price itemCategory:(NSString*)category itemDate:(NSDate*)date;
-(void)forDebug;
+(id)instance;
#end
MyApplicationData.m
#import "MyApplicationData.h"
#implementation MyApplicationData
+ (id)instance
{
static MyApplicationData* _instance = nil;
if (!_instance) {
_instance = [[MyApplicationData alloc] init];
}
return _instance;
}
-(void)loadData{
appData = [NSMutableArray array];
NSLog(#"%#",appData);
}
-(void)forDebug{
}
-(void)addAppDataItemPrice:(NSString*)price itemCategory:(NSString*)category itemDate:(NSDate*)date{
NSLog(#"%#", appData);
[appData addObject:#"1"];
NSLog(#"%#", appData);
}
#end
another class
[[MyApplicationData instance] loadData];
one another class
[[MyApplicationData instance] addAppDataItemPrice:price itemCategory:category itemDate:date];
log
[Session started at 2009-11-03 21:04:41 +0900.]
2009-11-03 21:04:44.742 XXX[24002:207] (
)
2009-11-03 21:04:46.612 XXX[24002:207] (null)
It is not executed. What is the cause?
I think this line might be the cause:
appData = [NSMutableArray array];
try this instead:
appData = [[NSMutableArray alloc] init]
You'll want to make sure you release it as well when your MyApplicationData instance is destroyed (not critical in this case since it's a singleton, but still good practice)
It looks like your array is getting autoreleased after the method:
[[MyApplicationData instance] loadData];
I think it should be a member of the class, you can use the property syntax to help.
Set it up in the header file as:
#property (nonatomic, retain) NSMutableArray *appdata;
Then in the implementation:
#synthesize appdata;
Assign it as follows:
-(void)loadData{
self.appData = [NSMutableArray array];
}
Don't forget to release it in your dealloc method
When you set it in your code you can call it like the following:
[self.appData addObject:#"1"];