Checking NSMutableArray for 0 elements causes a crash; why? - objective-c

I have declared a NSMutableArray as a singleton; when I try to check for the array count, the app crashes! Here is the code:
// clear array that holds selected servcies
SingletonArrayOfSelectedRows *arrayOfSelectedRows = [SingletonArrayOfSelectedRows sharedArrayOfSelectedRows];
if([arrayOfSelectedRows count] > 0)
[arrayOfSelectedRows removeAllObjects];
This code is the same code I have found all over SO and Google. Using XCode5, I have checked to make sure the singleton is allocated (and it is), and there is a valid count (0) for the singleton.
UPDATE
Here is the code for the singleton.h file:
#interface SingletonArrayOfSelectedRows : NSMutableArray {
}
#property (nonatomic, retain) NSMutableArray *arrayOfSelectedRows;
+ (id)sharedArrayOfSelectedRows;
#end
Here is the code for the singleton.m file:
#implementation SingletonArrayOfSelectedRows {
}
#synthesize arrayOfSelectedRows; // rename
// sharedSelectedCellIndexes
+ (id)sharedArrayOfSelectedRows {
static dispatch_once_t dispatchOncePredicate = 0;
__strong static id _sharedObject = nil;
dispatch_once(&dispatchOncePredicate, ^{
_sharedObject = [[self alloc] init];
});
return _sharedObject;
}
-(id) init {
self = [super init];
if (self) {
arrayOfSelectedRows = [[NSMutableArray alloc] init];
}
return self;
}
#end

Don't subclass NSMutableArray to do this. NSMutableArray is a class cluster. All of the actual array implementation is inside subclasses of NSMutableArray. If you subclass NSMutableArray then your subclass won't actually implement any array behavior unless you write it yourself.

According to the documentation :
Any subclass of NSArray must override the primitive instance methods count and objectAtIndex:.
Since you are subclassing NSMutableArray you will need to override the following NSMutableArray primitive methods as well:
insertObject:atIndex:
removeObjectAtIndex:
addObject:
removeLastObject
replaceObjectAtIndex:withObject:

Related

Singleton How to Declare NSMutableArray

I am trying to implement a singleton which contains an NSMutableArray* what I've done so far is below.
Singleton.h
#import <Foundation/Foundation.h>
#interface Singleton : NSObject{
NSMutableArray* ClassArray;
}
#property NSMutableArray* ClassArray;
+(Singleton*) getInstance;
- (void) SetClassArray:(NSMutableArray *)InputClassArray;
- (NSMutableArray*) GetClassArray;
Singleton.m
#import "Singleton.h"
#implementation Singleton
#synthesize ClassArray;
static Singleton *singletonInstance;
+ (Singleton*)getInstance{
if (singletonInstance == nil) {
singletonInstance = [[super alloc] init];
}
return singletonInstance;
}
- (void) SetClassArray:(NSMutableArray *)InputClassArray{
ClassArray = InputClassArray;
}
- (NSMutableArray*) GetClassArray{
return ClassArray;
}
#end
what I'm wondering is where does [[NSMutableArray alloc]init]; go? or do i not need it. Also when ClassArray is initialised i want some default values, (the return from another function,[DatabaseFunctions GetClassDefaultArray] ) again where does this go?. I'm assuming the line below singletonInstance = [[super alloc] init]; however it doesn't accept ClassArray.
I have an application consisting of four view controllers, what I need is an nsmutablearray that can be accessed and written to from any of these views. There are three others in total.
Thanks
I'm wondering is where does [[NSMutableArray alloc]init]; go? or do i not need it
That depends on what you expect in your getter. Is reasonable for your use case to return nil in GetClassArray?
You could guard against it by returning an empty array if it is nil:
- (NSMutableArray*) GetClassArray{
if ( ! ClassArray ) {
ClassArray = [[NSMutableArray alloc] init];
}
return ClassArray;
}
i want some default values
You can populate your array as you see fit whenever you want, the best place to start would probably be your init method:
+ (Singleton*)getInstance{
if (singletonInstance == nil) {
singletonInstance = [[super alloc] init];
NSMutableArray *array = ...;
[singletoneinstance SetClassArray:array];
}
return singletonInstance;
}
As a side note, I would recommend reading up on some naming conventions so you don't mixed up between class names and variable names in the future.

Static array in objective C

I use the following code to create a public static array in C#
public class A{
public static array[] obj;
}
I have another class B.
From class B I call
A.ArrayName and I get the array I use in class A.
I wanted to know, what is the equivalent of this in objective C
There is no special syntax for this. You just define a class method to return the static array.
For example:
#implementation A // note this is in the implementation
static NSArray *array;
+ (NSArray *)array
{
if (!array)
array = [[NSArray alloc] init];
return array;
}
#end
Or for messier code, but slightly better performance (a good idea in a tight loop, but usually not worthwhile):
#implementation A
static NSArray *array;
+ (void)initialize // this method is called *once* for every class, before it is used for the first time (not necessarily when the app is first launched)
{
[super initialize];
array = [[NSArray alloc] init];
}
+ (NSArray *)array
{
return array;
}
#end
To access it from class B you just do:[A array]
I want to propose using a Category on NSArray. I changed your requirement a bit to use an NSMutableArray as shared object.
interface file:
#import <Foundation/Foundation.h>
#interface NSArray (StaticArray)
+(NSMutableArray *)sharedInstance;
#end
implementation file
#import "NSArray+StaticArray.h"
#implementation NSArray (StaticArray)
+(NSMutableArray *)sharedInstance{
static dispatch_once_t pred;
static NSMutableArray *sharedArray = nil;
dispatch_once(&pred, ^{ sharedArray = [[NSMutableArray alloc] init]; });
return sharedArray;
}
#end
Now you can use it as:
[[NSArray sharedInstance] addObject:#"aa"];
[[NSArray sharedInstance] addObject:#"bb"];
[[NSArray sharedInstance] addObject:#"cc"];
and somewhere else:
NSLog(#"%#", [NSArray sharedInstance]);

iOS NSMutableArray Memory Leak

I'm having a bit of trouble with memory leaks in my objective c code. Could anyone take a look and let me know what they think?
NSStringArray.h
#interface NSStringArray : NSObject {
NSMutableArray *realArray;
}
#property (nonatomic, assign) NSMutableArray *realArray;
-(id)init;
-(void)dealloc;
#end
NSStringArray.m
#import "NSStringArray.h"
#implementation NSStringArray
#synthesize realArray;
-(id)init {
self = [super init];
if ( self != nil ) {
realArray = [[[NSMutableArray alloc] init] retain];
}
return self;
}
-(void)dealloc {
[realArray release];
realArray = nil;
[super dealloc];
}
Factory.m
+(NSStringArray *)getFields:(NSString *)line {
//Divides the lines into input fields using "," as the separator.
//Returns the separate fields from a given line. Strips out quotes & carriage returns.
line = [line stringByReplacingOccurrencesOfString:#"\"" withString:#""];
line = [line stringByReplacingOccurrencesOfString:#"\r" withString:#""];
NSStringArray *fields = [[NSStringArray alloc] init];
for (NSString *field in [line componentsSeparatedByString:#","]) {
[fields.realArray addObject:field];
[field release];
}
return [fields autorelease];
}
The Leaks tool is saying that the leak occurs when fields is allocated, and when I am adding field string to the fields array.
Also, this function is getting called each line of a file that I'm parsing.
Any tips would be helpful.
Thanks!
This line does a double retain:
realArray = [[[NSMutableArray alloc] init] retain];
it is enough
realArray = [[NSMutableArray alloc] init];
In this piece of code, you break the memory management rules.
for (NSString *field in [line componentsSeparatedByString:#","]) {
[fields.realArray addObject:field];
[field release];
}
You do not own the object pointed at by field so you must not release it.
You have overreleased field so the last object to release it (the autorelease pool in your case) is releasing an already dealloc'd object.
From the docs:
An allocation message does other important things besides allocating
memory:
It sets the object’s retain count to one (as described in “How Memory
Management Works”).
Therefore, you don't need to retain something that you've just alloc'ed.
Adding to Felz answer above. Use self.realArray when allocating array
self.realArray = [[NSMutableArray alloc] init];
Because you have created a property for the array so it is better to use "self"
You could also take advantage of the properties in objective C to make
more clear and efficient your code:
NSStringArray.h
#interface NSStringArray : NSObject {
}
#property (nonatomic, retain) NSMutableArray *realArray;
#end
NSStringArray.m
#import "NSStringArray.h"
#implementation NSStringArray
#synthesize realArray = _realArray;
-(id)init {
self = [super init];
if (self) {
self.realArray = [NSMutableArray array];
}
return self;
}
-(void)dealloc {
[_realArray release];
[super dealloc];
}
Now, with the modifier retain of the property realArray you can use
[NSMutableArray array] that return an autorelease mutable array.
The retain properties manage the retain/release stuff by themselves.
You don't need to use the realArray = nil; line. You've already deallocated
the property.
Hope this can help.

#property retain OR copy

First I read this article
I think I should use "copy" in my programe.
Problem is using NSMutableDictionary copy it will terminate.
***** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[__NSCFDictionary removeAllObjects]: mutating method sent to immutable object'**
I have no idea about "mutating method sent to immutable object".
I didn't set NSDictionary to NSMutabledictionary pointer.
Here is my code
.h file
#interface Button : NSObject {
#private
NSString* gID;
NSString* gBackColor;
NSString* gIconImage;
int gIndex;
BOOL gEnable;
BOOL gVisible;
NSString* gText;
NSMutableDictionary* gEvents;
BOOL gUseCircle;
}
#property (nonatomic,copy) NSString *ID;
#property (nonatomic,copy) NSString *BackColor;
#property (nonatomic,copy) NSString *IconImage;
#property int Index;
#property BOOL Enable;
#property BOOL Visible;
#property (nonatomic,copy) NSString *Text;
#property (nonatomic,getter=getEvents,retain) NSMutableDictionary *Events;
#property BOOL UseCircle;
#end
.m file
#implementation Button
#synthesize ID = gID;
#synthesize BackColor = gBackColor;
#synthesize IconImage = gIconImage;
#synthesize Index = gIndex;
#synthesize Enable = gEnable;
#synthesize Visible = gVisible;
#synthesize Text = gText;
#synthesize Events = gEvents;
#synthesize UseCircle = gUseCircle;
-(NSMutableDictionary*) getEvents
{
if (!gEvents)
{
gEvents = [[NSMutableDictionary alloc] initWithCapacity:20];
}
return gEvents;
}
- (id) init
{
self = [super init];
if (self != nil)
{
gID = #"";
gBackColor = #"";
gIconImage = #"";
gIndex = 0;
gText = #"";
gUseCircle = NO;
}
return self;
}
- (void) dealloc
{
[gID release];
[gBackColor release];
[gIconImage release];
[gText release];
[gEvents removeAllObjects];
[gEvents release];
gEvents = nil;
[super dealloc];
}
And implement
tBtnXML.Events = [self SplitEvents:tNode];
SplitEvents function:
-(NSMutableDictionary*) SplitEvents:(NSDictionary*)pEvents
{
NSMutableDictionary *tEvents = [[NSMutableDictionary alloc] initWithCapacity:5];
// code blabla
//.
//.
//.
[tEvents setObject:tEvent forKey:[NSNumber numberWithInt:tEventName]];
[tEvent release];
return [tEvents autorelease];
}
But I chage NSMutableDictionary* gEvents property from copy to retain , it execute normal.
Colud anyone tell me what's wrong with my code?
If my code is incorrect with dealloc,please tell me.
Thank you appriciate.
Yes, So I fixed my setter:
-(void) setEvents:(NSMutableDictionary*) pEvents
{
NSMutableDictionary* tNewDict = [pEvents mutableCopy];
[gEvents removeAllObjects];
[gEvents release];
gEvents = tNewDict;
}
This work with no error.
It helps me a lot.
But I can't vote up >"<~
So thank you Bavarious :)
In general, mutable properties should be retain instead of copy. When you declare a property as being copy, the synthesised setter method sends -copy to the object that’s being assigned to the property. In the case of mutable objects (e.g. NSMutableDictionary), sending -copy to them makes an immutable copy, effectively creating an object of immutable type (e.g. NSDictionary) instead.
So in:
tBtnXML.Events = [self SplitEvents:tNode];
the synthesised setter sends -copy to [self SplitEvents:tNode], thus creating an immutable copy of that dictionary (i.e., an NSDictionary instance), and assign it to gEvents. This is the cause of your error: gEvents is declared as NSMutableDictionary but points to an NSDictionary instead.
For the record, mutable classes usually declare a -mutableCopy method that does make a mutable copy. It is not used by declared properties, though. If you do not want to use retain, you need to implement a custom setter that uses -mutableCopy.

Using self.objectname causes profiler to report a memory leak

Please help;
Header File
#import <Foundation/Foundation.h>
#interface MyClass : NSObject {
NSMutableString * myString;
}
#property (nonatomic, retain) NSMutableString * myString;
-(id) init;
-(void) dealloc;
#end
Implementation File
#import "MyClass.h"
#implementation MyClass
#synthesize myString;
-(id) init {
if ((self = [super init])) {
self.myString = [[NSMutableString alloc] init];
}
return self;
}
-(void) dealloc {
[super dealloc];
[self.myString release];
}
#end
Usage
MyClass * m = [[MyClass alloc] init];
[m release];
//-- Xcode 4 profiler reports a memory leak here.
However, when the code in implementation file of the class is changed to not use the [self.myString .....] notation, then no memory leak is reported.
So,
-(id) init {
if ((self = [super init])) {
myString = [[NSMutableString alloc] init];
}
return self;
}
}
and
-(void) dealloc {
[super dealloc];
[myString release];
}
works fine. No memory leaks reported.
Any ideas - is it profiler or is it me (be nice)?
Your memory leak is not caused by using your setter. Your memory leak is caused by you not managing your memory correctly!
If you declare the following property
#property (nonatomic, retain) id value;
That means that the compiler generates methods that look something like this (highly simplified):
- (id)value {
return value;
}
- (void)setValue:(id)aValue {
[value autorelease];
value = [aValue retain];
}
When you use dot-notation, self.value = obj is desugared into [self setValue:obj]. Thence, you are actually causing obj to be retained within the setter. If you initially create an owning reference to obj (by using an +alloc without a corresponding -release or -autorelease), you'll have over-retained obj, and it will never be deallocated. Hence, you need to do something like this:
id obj = [[[NSObject alloc] init] autorelease];
self.value = obj;
or
id obj = [[NSObject alloc] init];
self.value = [obj autorelease];
or
id obj = [[NSObject alloc] init];
self.value = obj;
[obj release];
Whatever you do, you need to make sure that when you assert ownership of an object (by retaining it), you also release it.
Setter methods in Objective-C equate to a reatain of the new object and release of the old object. In your case the compiler will generate a setter method for your myString property that looks something like...
- (void)setMyString:(NSMutableString*)aString {
[myString autorelease];
myString = [aString retain];
}
When you invoke self.myString = in your init method this translates to a call to the setter. The setter in turn retains the object you pass to it. Because you've directly alloc'd the NSString it begins life with a retain count of one, you then call the setter and the retain count becomes two.
There's two approaches to fixing the problem, the first would be to add a call to [myString autorelease] after you alloc it. Or secondly switch your init method to directly assign the ivar...
// in your init method...
myString = [[NSMutableString alloc] init];
It's a good idea to avoid setter usage in init methods, not because of retain counts but because the object as a whole is not yet fully initialized.
#property (nonatomic, RETAIN)
you are retaining my friend. You have to release the object twice then because the retain count is 2
here is what you should do in the INIT method:
NSString *str = [[NSString alloc] initWithString:#"Hello World!"];
self.myString = str;
[str release]; // dont leak
Also I do not recommend using self.someProperty in the class itself. Doing so requires 1 extra objc_msgSend() to be done to access your variable and will slow down your application.