Creating a 2D array in Objective-C with a variable size is simple and straightforward

I've recently started learning objective-c and I'm facing some challenges with 2D arrays. To help explain my issue, I'll make use of my knowledge in javascript.

var row = 10;
var col = 10;
var array[row][col];

for (var i = 0; i < row; i++){
    for (var j = 0; j < col; j++){
        //do something here
    }
}

row = 20;
col = 20;

for (var i = 0; i < row; i++){
    for (var j = 0; j < col; j++){
        //do something here
    }
}

I'm looking to implement this logic in objective-c. Any suggestions on how I can achieve this?

Answer №1

Here is a helpful guide:

NSInteger row = 10;
NSInteger col = 10;

// Creating an array with dynamic size.
NSMutableArray* array = [NSMutableArray new];

for (NSInteger i = 0; i < row; i++) {

    // Values must be added before accessing them.

    NSMutableArray* colArray = [NSMutableArray new];
    [array addObject:colArray];

    for (NSInteger j = 0; j < col; j++) {


        [colArray addObject:someObject];

        // Accessing elements in the array:
        id object = array[i][j];

        // Modifying existing values in the array:
        array[i][j] = someObject;

        // Using NSNull to represent null values instead of nil or null:
        array[i][j] = [NSNull null];
    }
}


// Initializing an array with predefined values:

NSArray* anotherArray = @[objectOne, objectTwo, objectThree];

// Creating a 2-dimensional array:

NSArray* twoDimensionalArray = @[
                                 @[rowOneColumnOne, rowOneColumnTwo, rowOneColumnThree],
                                 @[rowTwoColumnOne, rowTwoColumnTwo, rowTwoColumnThree]
                                 ];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property? items() { return this.table.filter.keyword ? this.dataArray.filter( item => item.nombre.toLowerCase().includes(t ...

Steer clear of making changes to a JavaScript array

Here is my code snippet: let traces = { ref: null, min: null, max: null, avg: null }; let learning = { "Application": "b3", "t": [ { "d": 2, "BinaryType": "Current" }, { "d": 3, ...

The parameter 'Value | ValueXY' cannot be assigned to the type 'AnimatedValue<0>'

Recently, I delved into React Native documentation on Animations which can be found here: https://reactnative.dev/docs/animated After reading the docs, I decided to try out some code snippets: import {Animated as RNAnimated} from 'react-native' ...

Guide on decrypting a file encrypted with C# using Node JS

I currently have encrypted files in C# using DES and PKCS7 encryption. My objective is to decrypt these files in Node JS. The decryption code in C# that I am using appears like this: public string SSFile_Reader( string fileToDecrypt ) { DESCryptoService ...

Creating a custom loading spinner using HTML and CSS

I am looking to create a spinner using just the <input> element. The only element I can utilize is <input type="text" placeholder="Select Date" class="sel1" /> How can I use CSS to implement a basic spinner in this scenario? ...

What is the best way to allow my limit to be as greedy as possible?

I'm facing an issue with the code below where it currently only matches MN. How can I modify it to also match KDMN? var str = ' New York Stock Exchange (NYSE) under the symbol "KDMN."'; var patt = new RegExp("symbol.+([ ...

Ways to segment into a proper array

I received the following object from an API and I am looking to convert it into an array using either JavaScript or C#. [ "1":"h1:first", "2":".content a > img", "3":"#content div p" ] I attempted converting it to a JSON object and using the spl ...

Using Angular $scope in web workers

What is the best way to access angular $scope data in Web Workers? I'm currently experimenting with using parallel.js library for this purpose. $scope.variant = 7; $scope.final = 0; var p = new Parallel([0, 1, 2, 3, 4, 5, 6]), log = function () { co ...

Tesseract on iOS having trouble with recognition

Looking at the image here: https://i.sstatic.net/MF8SV.jpg I attempted to use Tesseract to recognize the letters, but all I get is some gibberish like _u_i.i_1, L_n_.t. Here's the code I'm using: let tesseract = G8Tesseract.init(language: "eng" ...

Difficulty fetching css files on handlebars (express API)

Recently, I encountered an issue where the CSS styles were not being applied to my HBS code despite several attempts. The structure of my service is as follows: Service Controllers Models public css styles.css Routers Views index.hbs app.js pac ...

Is it more effective to store data in markers or in JSON when using the Google Maps JS API?

I have been working on visualizing government data through the Google Maps JS API. Currently, every time a user changes a filter value, the whole JSON dataset is fetched again, filtered, and new markers are generated for each valid row. This process seems ...

Troubleshooting Navigation Bar Toggle Button Issue in Bootstrap 5

Currently, I am in the process of working on a web project that requires the implementation of a responsive sidebar. This sidebar should be toggleable using a button located in the navigation bar. My choice for the layout is Bootstrap, and I have come acr ...

Version 13 of the Discord slash command encounters an "interaction failed" error

After implementing the slash commands in Discord v13 as per the instructions on discordjs.guide, I encountered an issue when trying to use the commands - interaction failed. Here is a snippet of my code: // Here goes the code const { Client, Collection, ...

Merge HTML code with JavaScript from Fiddle

There was a similar inquiry posed in this specific forum thread, however, I am encountering difficulties converting the code from JSfiddle to HTML. You can access the JSfiddle example through this link: here. I attempted to apply the suggested technique ...

"Enhance your React application with react-router-dom by including parameters in the index URL while also

Here is the code I am currently using: <Router history={history}> <div> <Route exact path="/:id?" component={Container1} /> <Route path="/component2/ component={Container2} /> </div> </Router> When accessin ...

Pressing a button will display a div element, which will automatically be hidden after 5 seconds

I'm working on an email submission form that displays a confirmation message below the input field when a user submits their email address. The confirmation text should fade out after 5 seconds. Here's the code snippet: <div class="input-gro ...

Element with adhesive properties alters its color at a particular location

I need the sticky element to change colors at specific points and then revert back to its original color. The color should be orange initially, green on block 2, and orange again on block 3. For the complete code and to address any issues with jQuery, pl ...

What causes my array of objects to be assigned numbers when copying a JSON data file using Object.assign?

I have a JSON file that I need to transfer to my local object using new Object and Object Assign: let newObj = new Object(); Object.assign(newObj, MyData.map(data => ({ personal_id : data._id, idx : data.index, voiceLines : data.tags }))); console.log ...

Calculate the total sum of the properties of the objects within the array

I need to calculate the total sum of unit prices. Any suggestions on how I can achieve this? This is what the array looks like: $scope.items = [ { id: '1', name: 'Phone', quantity: '1', u ...

Is there a quick way to use AJAX in Rails?

By using the remote:true attribute on a form and responding from the controller with :js, Rails is instructed to run a specific javascript file. For instance, when deleting a user, you would have the User controller with the Destroy action. Then, you woul ...