Problems sending messages to NSMutableArrays within C-Arrays - objective-c

I'm currently trying to implement a pooling system, I have all the code, I just dont understand why a certain part of it doesn't work.
I have a c-array of NSMutable array made like this:
NSMutableArray *poolArray[xSize][ySize];
for (int n = 0; n < xSize; n++)
{
for (int m = 0; m < ySize; m++)
{
poolArray[n][m] = [[NSMutableArray alloc] init];
}
}
And whilst trying to access it I get the x and y coordinate of the pool and object is in and try to add it like this:
[poolArray[x][y] addObject:object]; //This raises a EXC_BAD_ACCESS error
I am totally open to editing how I write this - I am aware that I could declare a NSMutableArray and use indexes of ((y * width) + x) and I may have to rewite the code like that. But preferably I dont want to have to do that as I only want to actually create the arrays I'm using so something like this:
if (poolArray[x][y] == nil) poolArray[x][y] = [[NSMutableArray alloc] init];
[poolArray[x][y] addObject:object];
This is so that it can have 'holes' so I dont have to make anything at poolArray[2][3] for example if there is nothing there.
I don't know if there is anyway that I could rewrite that with objective-c types, but if I do I'm forced to keep creating a NSMutableArray at every space, the reason I dont want to do that is because I want to get every little bit of performance I can out of the system.
Thanks for taking the time to read this, and any response is appreciated :)

This works for me:
#import <Foundation/Foundation.h>
#define xSize 10
#define ySize 10
int main (int argc, const char * argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *poolArray[xSize][ySize];
for (int n = 0; n < xSize; n++)
{
for (int m = 0; m < ySize; m++)
{
poolArray[n][m] = [[NSMutableArray alloc] init];
}
}
[poolArray[2][3] addObject: #"Hello"];
[poolArray[2][3] addObject: #"world!"];
NSLog(#"poolArray[2][3] objects: %# %#",
[poolArray[2][3] objectAtIndex: 0],
[poolArray[2][3] objectAtIndex: 1]);
[pool drain];
return 0;
}
(Yes, I know, I should release all NSMutableArray instances. Left out for brevity).
So there are a few things you should check:
Is object a valid object, i.e. was it initialized? The NSMutableArray will try to retain the object, and if it was never initialized, that will fail miserably, or if it was dealloc-ed already, it will fail too.
are x and y valid? You can easily go over the boundaries and not notice it.

Can't see anything wrong with the code you've provided, although a couple of ideas:
In the case where your checking poolArray[x][y] == nil have you actually reset all the values to nil when you initialize the array?
An alternative that should work, is to store the array on the heap. You could use calloc (which will initialize the memory to 0), or malloc and memset.
The following should work:
NSMutableArray ***poolArray = calloc(xSize * ySize, sizeof(NSMutableArray *));
if (poolArray[x][y] == nil) poolArray[x][y] = [[NSMutableArray alloc] init];
[poolArray[x][y] addObject:object];

Related

dispatch_apply gives incorrect output data

I have two arrays: array1 and array2. Each object of arrays is an array too (2D arrays). In this way I multiple them. So how I have big arrays I use dispatch_apply. Every time i receive different results include a right result. Maybe somebody knows how to fix it?
dispatch_apply([array2 count], queue, ^(size_t j)
{
k = 0;
for (int l = 0; l < [[array1 objectAtIndex:0] count]; l++) {
k += [[[array1 objectAtIndex:i] objectAtIndex:l] intValue] *
[[[array2 objectAtIndex:j] objectAtIndex:l] intValue];
}
kNSNumber = [NSNumber numberWithInt:k];
[multipliedArrayInto replaceObjectAtIndex:j withObject:kNSNumber];
});
[resulArray insertObject:multipliedArrayInto atIndex:i];
}
There's two things, I can suggest, and I bet one of them (or both) is the overarching solution to your problem.
First, I would declare k local to the block, so there would be no question that you are overwriting it or not. You likely have the same problem with kNSNumber inside the block. If you are just using that NSNumber instance to slam into the multipliedArrayInto accumulator, you may as well remove kNSNumber, and use #(k) in it's place (if only to be more readable). Similarly, make sure multipliedArrayInto is declared just before the dispatch_apply, in what looks like an outer for loop (where ever i is coming from). And finally, make sure resulArray is instantiated, or otherwise readied just before that outer for loop.
Second, is queue a concurrent or serial queue? If you are using dispatch_apply like a parallel-executing for/enumeration -- which is likely, I think, so you are taking about handling "big arrays" efficiently -- then you are practically guaranteeing that k is being overwritten. If you change it to serial, it may work as designed. If you want it to be parallel, you will need to move the declaration of your k accumulator inside the block, and make sure the declaration of other variables makes sense, too.
Update to reflect question updates:
#antonytonies ideally, your followup answer on this thread should be moved into the question itself, so that people can follow this thread easier.
So, it looks like what I described is exactly your problem.
The global queues are all concurrent queues, which means that (hypothetically) all the dispatch blocks are executing at once, and the contents of k and other variables are getting blown away depending on how the order of the blocks executes.
I've taken your update (in the "answer" you added), and modified it to probably work:
// I renamed your method, because nameless parameters pain me. This is cosmetic, and doesn't
// matter for the problem at hand.
- (NSMutableArray *)multiplicationArrays:(NSMutableArray *)array vector:(NSMutableArray *)vector
{
// IMHO, you want to set resultArray to nil here. Another option is to set it to nil in the
// else case, below. Properties in Objective-C are initalized to nil,0,false,etc; you can
// rely on ARC to initialize pointer to objc objects on the stack, too. However, someone
// reading this code may or may not know that. IMHO, using the explicitly assignement makes it
// clear that you're going to be returning `nil` or an instance of `NSMutableArray`.
NSMutableArray *resultArray = nil;
if ([[array objectAtIndex:0] count] == [vector count]) {
// Nicely done w/ pre-allocating the result array here, so that there's no question
// of the indexes matches the results later on.
resultArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
for (int i=0; i < [array count]; i++) {
[resultArray insertObject:[NSNull null] atIndex:i];
}
// 'queue' here is a concurrent queue. This means that you are proclaiming to the runtime
// that the blocks being executed are able to operate correctly w/o interference from each
// other. This is also thought of in terms of parallel execution: all these blocks may run
// **at once**. This *also* means, that you must not share storage between them.
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t j) {
// Moved 'result' inside the block.
NSInteger result = 0;
for (int l = 0; l < [[array objectAtIndex:0] count]; l++) {
// These array reads are **NOT** thread safe. They probably don't cause must trouble in
// practice, but you may want to reconfigure this.
result += [[[array objectAtIndex:j] objectAtIndex:l] intValue] * [[vector objectAtIndex:l] intValue];
}
// The replace of the object into resultArray is **NOT** thread-safe.
// This probably hasn't caused you much trouble, since you can guarantee that
// you aren't writing at the same index. However, I would strongly suggest to
// change this to be thread-safe.
[resultArray replaceObjectAtIndex:j withObject:#(result)];
});
}
else {
NSLog(#"matrix count isn't correspond");
}
return resultArray;
}
Finally: consider just using Apple's Accelerate framework for this sort of problem solving. It's available on OSX and iOS, so you should have all of your bases covered.
it's the same thing if I multiple 2D-array and vector
-(NSMutableArray*)multiplicationArraysWithVector:(NSMutableArray *)array :(NSMutableArray *)vector
{
NSMutableArray* resultArray;
if ([[array objectAtIndex:0] count] == [vector count])
{
resultArray = [[NSMutableArray alloc] initWithCapacity:[array count]];
for (int i=0; i < [array count]; i++) {
[resultArray insertObject:[NSNull null] atIndex:i];
}
__block NSInteger result;
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_apply([array count], queue, ^(size_t j)
{
result = 0;
for (int l = 0; l < [[array objectAtIndex:0] count]; l++) {
result += [[[array objectAtIndex:j] objectAtIndex:l] intValue] * [[vector objectAtIndex:l]intValue];
}
[resultArray replaceObjectAtIndex:j withObject:#(result)];
});
}
else
{
NSLog(#"matrix count isn't correspond");
}
return resultArray;
}
In this case I can get a right or wrong data result.

NSArray not deallocating in ARC Objective-C

I am trying to write a command line application in Objective-C for a university project. The project needs matrix manipulation so I have written a class to handle all the matrix methods (Addition and multiplication and such). My matrix methods look like this:
- (NSArray *)sumMatrices:(NSArray *)matrices
{
NSMutableArray *sum = [[NSMutableArray alloc] init];
NSInteger cols = [matrices[0][0] count];
NSInteger rows = [matrices[0] count];
for (int i = 0; i < rows; i++) {
NSMutableArray *row = [[NSMutableArray alloc] init];
for (int j = 0; j < cols; j++) {
CGFloat value = 0.0;
for (NSArray *array in matrices) {
value += [array[i][j] doubleValue];
}
[row addObject:[NSNumber numberWithDouble:value]];
}
[sum addObject:[row copy]];
row = nil;
}
return [sum copy];
}
However theres is a massive problem with this programme, I having used objective-c for iOS expect ARC to handle all my memory allocation and deallocation without a problem, however in this case the NSMutableArray 'sum' is never being deallocated, and because this method is being called in a loop which runs 10's of thousands of times (Modelling a double pendulum using RK4) the memory usage builds up and makes the program extremely slow.
Is there any reason this NSMutableArray isn't being deallocated once this method has returned?
Your problem is less about this code and more about the code surrounding it. Let's assume for a moment that your code around it looks like this:
NSArray *matricies; //Declared somewhere else;
NSMutableArray *results = [[NSMutableArray alloc] init];
for (int i=0; i < [matricies count] - 1; i++) {
for (int j=i+1; j < [matricies count]; i++) {
NSArray *sum = [self sumMatrices:#[matricies[i], matricies[j]]];
[results addObject:sum];
}
}
The actual operations that I'm performing are not particularly relevant to this example. The code pattern is. You'll notice I'm using a nested "tight" loop. Control never returns to the run loop until AFTER all calculations are complete. Without ARC, your memory would be freed as soon as the last release was performed, excluding autoreleased objects. With ARC, your memory is not freed until control is returned to the runloop, much the same way autoreleased objects used to. As a result, your code will appear to leak, until processing is complete and the system decides it should release your memory. If the CPU is perpetually under a heavy load, it may not clean up memory until it absolutely has to.
There are a few cleaver ways to use #autoreleasepool to help in this case, but that will make your code significantly slower. Additionally, Objective C is a fairly slow language for objects and method calls. If you are using this code heavily, you should convert it into C or C++ and manage the memory yourself.
without going into much detail you can try to use autoreleasepool
https://developer.apple.com/library/mac/documentation/cocoa/conceptual/memorymgmt/articles/mmAutoreleasePools.html
i would use copy if i want to preserve an array which gets modified but in your case do you really need it ?

Storing objects in an array in objective c

I'm trying to store 25 objects in an array
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[TerrainHexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [TerrainHexArray count]);
The log is coming back as zero though.
In the .h file I have
#property NSMutableArray *TerrainHexArray;
And in the .m file I have..
#synthesize TerrainHexArray;
I just tried what someone suggested below, which is..
NSMutableArray *TerrainHexArray = [[NSMutableArray] alloc] init];
But it's just giving me a warning saying expected identifier.
It's almost certain that TerrainHexArray does not exist when you're doing the addObject calls and the NSLog. You say you tried adding the alloc/init after someone suggested it, which indicates you don't understand object management in Objective-C.
I'd suggest you step back, find a book on Objective-C, and read at least the first few chapters (up through the discussion of alloc/init et al) before you attempt any more coding.
Incidentally, it's standard C++/Objective-C coding practice (except in Microsoft) to use identifiers with a leading lower case character for instance names, reserving leading caps for types/class names.
What is TerrainHexArray? It looks like a class name, not an instance of an array. If you create a mutable array, then you can add the items to the array.
NSMutableArray *hexArray = [[NSMutableArray] alloc] init];
for (int iy=0; iy<5; iy++) {
for (int ix=0; ix<5; ix++) {
TerrainHex *myObject = [[TerrainHex alloc] initWithName:(#"grassHex instance 10000") width:mGameWidth height:mGameHeight indexX:ix indexY:iy];
myObject.myImage.y += 100;
[hexArray addObject:myObject];
[self addChild:(id)myObject.myImage];
}
}
NSLog(#"Terrain array: %u", [hexArray count]);

Creating 20 objects in a loop

I need some newbie help.
So basically im trying create 20 individual objects (players). Each player has a name , age and height.
Instead of writing 'Person *player = [[Person alloc] init];' Twenty times, I have made a loop.
I think the loop has worked because the [myArray count] has 20 objects.
My questions:
Are the 20 objects unique ( all with same name, age, height) ?
Whats the best way to give each object in each element of MyArray a name,age,height ?
So my end goal is to be able to do something like this:
NSLog(#"%# is %i high and is %i years old", player1.name, player1.height, player1.age);
NSLog(#"%# is %i high and is %i years old", player2.name, player2.height, player2.age);
etc...
I hope the above makes sense and I really appreciate your help.
#import <Foundation/Foundation.h>
#import "Person.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *myArray = [[NSMutableArray alloc]initWithCapacity:20];
for (int i = 0; i < 20; i++)
{
Person *player = [[Person alloc] init];
player.age = 10;
player.height = 10;
player.name = #"player";
[myArray addObject:player];
[player release];
}
NSLog(#"The number of players in myArray = %i", [myArray count]); // I now have 20 players (objects) in myArray.
//How can I now give each player object an individual name, age & height ??
[pool drain];
return 0;
}
Are the objects unique? YES, they are.
What the best way to give each object a name,age,height? this question is not clear, so the way you gave an age, height and name to your objects in the loop is correct but of course you're providing the same info to all objects; giving them unique names depends on your application logic, for example you could assign the age randomly in this way:
player.age = arc4random()%90;
You can do the same for the height (eventually with a slightly more complicated formula, e.g. 140+arc4random()%50). Finally for the height you can assign a derived name in this way:
player.name = [NSString stringWithFormat:#"Player-%d",i];
which assigns names Player-0, Player-1, ...
Finally to print-out the data in the NSLog:
NSLog(#"Player %d : name=%# height=%d age=%d",i,player.name,player.height,player.d)
or in a different loop:
int i = 0;
for(Person *player in myArray) {
NSLog(#"Player %d : name=%# height=%d age=%d",i,player.name,player.height,player.d);
i++;
}
A couple of items.
If I understand your follow up question properly, what you are looking to do is access the objects you have stored in your array so that you can change the values of their properties.
However, the above poster answered the actual question you asked, and you should mark his correct.
If you wanted to go through each item in the array you would do the following:
for (int i=0; i<[players count]; i++) {
Player *aPlayer = [players objectAtIndex:i];
aPlayer.name = #"joe";
}
If you only wanted to access a single player:
Player *aPlayer = [players objectAtIndex:4];
aPlayer.name = #"joe";
Also you may want to customize your Player class and override the description so that you don't have to repeatedly type complex NSLog statements.
-(NSString *)description{
return [NSString stringWithFormat:#"name = %# age = %d height = %d", self.name, self.age, self.height];
}
By overriding the description method calling NSLog on your object will return the string from this statement.

Multidimensional arrays - what's the most convenient way to work with them in Objective-C?

I'm a beginner in Objective-C and I'm trying to find the most convenient way to work with multidimensional arrays in Objective-C. Either I am missing something or they are very ugly to work with.
Let's say we have a classic problem:
read input from file; on the first line, separated by space(" ") are the width and height of the matrix (eg: 3 4)
on the following lines there is the content described by the values above
Eg:
3 4
a b c d
e f g h
i j k l
The first solution I thought of was:
NSMutableArray *matrix = [[NSMutableArray alloc] initWithCapacity: x]; //x = 3 in this specific case
NSMutableArray *cell;
for(cell in matrix)
{
cell = [NSMutableArray initWithCapacity: y];
for(int i = 0; i < y; i++) // y = 4
{
//object is a NSString containing the char[i][j] read from the file
[cell insertObject:object atIndex: i];
}
}
This was the first thing I had in mind when thinking about how I should get my values read from file in a multidimensional array. I know you can use C arrays, but since I will store NSObjects in it, I don't think is such a great idea. Nonetheless, from my point of view is easy to work with C arrays rather the solution I got with Objective-C.
Is there another way you could build a multidimensional array in obj-c and easier than the one above?
How about looping them?
I know I can do something like
NSArray *myArray;
for(int i=0; i < [array count]; i++)
{
[myArray arrayWithArray: [array objectAtIndex: i]];
for(int j=0; j < [myArray count]; j++)
{
NSLog(#"array cell [%d,%d]: %s", i, i, [myArray objectAtIndex: j]);
}
}
But that is still more complicated than your average C multidimensional array loop.
Any thoughts on this?
Objective-C is a superset of C, if you want to work with multidimensional arrays like you would in C, do it that way. If you want to work with objects doing it the Cocoa way, then that's fine too, but you will write more code to do it.
Can you not simply make an array of id?
#import <Foundation/Foundation.h>
int main(int argc, char **argv) {
id ptr[3][4];
NSObject *p;
ptr[0][0] = p;
}
You can do nothing more with NSArray or NSMutableArray in this regard. That is there is nothing like objectAtIndex:i :j
You can always create one-dimensional arrays of the size width * height instead:
const int size = width*height;
NSMutableArray *array = [NSMutableArray arrayWithCapacity:size];
for (int i=0; i<size; ++i) {
NSString *string = [NSString stringWithFormat:#"col=%d, row=%d", i%width, i/width];
[array insertObject:string atIndex:i];
}
Nobody uses direct multi-dimensional arrays of any size in any computer language (except for homework). They simply use too much memory and are therefore too slow. Objective-C is an object-oriented language. Build a class that does what you need.