Index is out of range on main - objective-c

I am trying to make one sdk working however is in objective C and. I am very new to this..like two hours. Index is out of range on main I guess means that some page is missing ?
Thread 1 index is out of range
int main(int argc, char * argv[]) {
NSString * appDelegateClassName;
#autoreleasepool {
// Setup code that might create autoreleased objects goes here.
appDelegateClassName = NSStringFromClass([AppDelegate class]);
}
return UIApplicationMain(argc, argv, nil, appDelegateClassName);
}
Edit
I am using simulator and the exception is in this first line
SettingHandler *videoFormat = [[SettingHandler alloc] initWithTitle:#"Video format" key:#"video_format" type:#"picker"];
HNfvcVideoFormat *formats;
NInt formatCount = 1;
NFaceVerificationClientGetAvailableVideoFormats(&formats, &formatCount);
NSMutableArray *formatList = [NSMutableArray array];
for (int i = 0; i < formatCount; i++) {
NUInt width;
NUInt height;
NFloat fps;
NFaceVerificationClientVideoFormatGetWidth(formats[i], &width);
NFaceVerificationClientVideoFormatGetHeight(formats[i], &height);
NFaceVerificationClientVideoFormatGetFrameRate(formats[i], &fps);
[formatList addObject:[NSString stringWithFormat:#"%d x %d # %d", width, height, (int)fps]];
}
[videoFormat setOptions:formatList];
and another here
SettingHandler *icaoSettings = [[SettingHandler alloc] initWithTitle:#"ICAO Settings" key:nil type:#"title"];

Related

Invalid memory reference (SIGSEGV) and incomplete implementation of class error

I am writing a small recursive function to calculate the sum of integers from an array. However, I am getting errors and warnings. Anybody help me to solve these issues?
#import <Foundation/Foundation.h>
#interface SumIntegers:NSObject
{
NSInteger result;
}
-(NSInteger)calcutateSum:(NSInteger)value;
-(void) printSum;
#end
#implementation SumIntegers
-(NSInteger)calculateSum:(NSInteger)value
{
NSInteger sum = 0;
//sum = sum + [[self calculateSum:[array objectAtIndex:i]] integerValue];
sum = sum + [self calculateSum:value];
result = sum;
return result;
}
-(void) printSum
{
NSLog(#"Sum of integer list is %i",result);
}
#end
int main (int argc, const char * argv[])
{
NSInteger i;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *intArray = [NSMutableArray arrayWithObjects:[NSNumber numberWithInteger:1],[NSNumber numberWithInt:3],[NSNumber numberWithInt:5]
,[NSNumber numberWithInt:7],[NSNumber numberWithInt:9],nil];
SumIntegers *sumIntegers = [[SumIntegers alloc]init];
for (i = 0; i<[intArray count]; i++)
{
NSInteger hhh = [sumIntegers calculateSum:[[intArray objectAtIndex:i] integerValue]];
}
[sumIntegers printSum];
[pool drain];
return 0;
}
What I did is I created an interface SumIntegers and created a recursive function to calculate the sum of integers. However, somehow this function is not recognized and also getting warning "incomplete implementation of class #end" and memory error.
Warning(s):
source_file.m:31:1: warning: incomplete implementation of class ‘SumIntegers’
#end
^
source_file.m:31:1: warning: method definition for ‘-calcutateSum:’ not found
source_file.m: In function ‘main’:
source_file.m:44:19: warning: unused variable ‘hhh’ [-Wunused-variable]
NSInteger hhh = [sumIntegers calculateSum:[[intArray objectAtIndex:i] integerValue]];
^
Error(s):
Invalid memory reference (SIGSEGV)
Here is my answer to above problem. There is no need of return value or argument in the calculateSum method. Simply adding array value into the sum and then calling the calculateSum method again until num is less than array count.
#import <Foundation/Foundation.h>
#interface SumOfIntegers:NSObject
{
NSMutableArray *intArray;
NSInteger sum;
NSInteger num;
}
#property NSMutableArray *intArray;
#property NSInteger sum, num;
-(void) calculateSum;
#end
#implementation SumOfIntegers
#synthesize intArray, sum, num;
-(void) calculateSum{
if(num < [intArray count])
{
NSLog(#"number is.... %i", num);
sum = sum + [[intArray objectAtIndex:num++] integerValue];
[self calculateSum];
}
else
{
NSLog(#"Sum of integers is %i", sum);
}
}
#end
int main (int argc, const char *argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [NSMutableArray arrayWithObjects:[NSNumber numberWithInteger:1],[NSNumber numberWithInt:3],[NSNumber numberWithInt:5]
,[NSNumber numberWithInt:7],[NSNumber numberWithInt:9],nil];
SumOfIntegers *sumOfIntegers = [[SumOfIntegers alloc]init];
sumOfIntegers.intArray = array;
sumOfIntegers.sum = 0;
sumOfIntegers.num = 0;
[sumOfIntegers calculateSum];
[pool drain];
return 0;
}
In modern ObjC:
int main(int argc, const char * argv[]) {
#autoreleasepool {
NSArray *nums = #[#(1), #(2), #(3)];
NSLog(#"%#", [nums valueForKeyPath:#"#sum.self"]);
}
return 0;
}

MacOS - Activate a window given its Window ID

Is it possible to activate (bring to the fore) a window based on the values returned from CGWindowListCopyWindowInfo? (i.e Using the window ID (kCGWindowNumber) or something else.)
Edit:
I should specify that my app (which would run with accessibility permissions) needs to be able to do this for windows of other apps.
Since posting the question I've discovered AXUIElementPerformAction. Am I going in the right direction with this?
Or is running AppleScript bridge within my code the best approach?
You can attach to a process by pid and get its windows. Then use kAXRaiseAction to bring them to front, like this:
AXUIElementRef element = AXUIElementCreateApplication(pid);
if (element) {
CFArrayRef array;
AXUIElementCopyAttributeValues(element, kAXWindowsAttribute, 0, 99999, &array);
if (array == nullptr)
return;
NSArray *windows = (NSArray *)CFBridgingRelease(array);
for (NSUInteger i = 0; i < windows.count; ++i) {
AXUIElementRef ref = (__bridge AXUIElementRef)(windows[i]);
AXError error = AXUIElementPerformAction(ref, kAXRaiseAction);
// handle error
}
}
CFRelease(element);
No need to release array or windows. Children in arrays are handled automatically and the array is bridged to an NSArray which is released by ARC.
My answer's a little overcomplicated compared to what was already shared by Mike Lischke, but I've already posted it on a different SO question and I think it is a tiny bit closer to what you need:
#import <Cocoa/Cocoa.h>
#import <libproc.h>
#import <string.h>
#import <stdlib.h>
#import <stdio.h>
bool activate_window_of_id(unsigned long wid) {
bool success = false;
const CGWindowLevel kScreensaverWindowLevel = CGWindowLevelForKey(kCGScreenSaverWindowLevelKey);
CFArrayRef windowArray = CGWindowListCopyWindowInfo(kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID);
CFIndex windowCount = 0;
if ((windowCount = CFArrayGetCount(windowArray))) {
for (CFIndex i = 0; i < windowCount; i++) {
NSDictionary *windowInfoDictionary = (__bridge NSDictionary *)((CFDictionaryRef)CFArrayGetValueAtIndex(windowArray, i));
NSNumber *ownerPID = (NSNumber *)(windowInfoDictionary[(id)kCGWindowOwnerPID]);
NSNumber *level = (NSNumber *)(windowInfoDictionary[(id)kCGWindowLayer]);
if (level.integerValue < kScreensaverWindowLevel) {
NSNumber *windowID = windowInfoDictionary[(id)kCGWindowNumber];
if (wid == windowID.integerValue) {
CFIndex appCount = [[[NSWorkspace sharedWorkspace] runningApplications] count];
for (CFIndex j = 0; j < appCount; j++) {
if (ownerPID.integerValue == [[[[NSWorkspace sharedWorkspace] runningApplications] objectAtIndex:j] processIdentifier]) {
NSRunningApplication *appWithPID = [[[NSWorkspace sharedWorkspace] runningApplications] objectAtIndex:j];
[appWithPID activateWithOptions:NSApplicationActivateAllWindows | NSApplicationActivateIgnoringOtherApps];
char buf[PROC_PIDPATHINFO_MAXSIZE];
proc_pidpath(ownerPID.integerValue, buf, sizeof(buf));
NSString *buffer = [NSString stringWithUTF8String:buf];
unsigned long location = [buffer rangeOfString:#".app/Contents/MacOS/" options:NSBackwardsSearch].location;
NSString *path = (location != NSNotFound) ? [buffer substringWithRange:NSMakeRange(0, location)] : buffer;
NSString *app = [#" of application \\\"" stringByAppendingString:[path lastPathComponent]];
NSString *index = [#"set index of window id " stringByAppendingString:[windowID stringValue]];
NSString *execScript = [[index stringByAppendingString:app] stringByAppendingString:#"\\\" to 1"];
char *pointer = NULL;
size_t buffer_size = 0;
NSMutableArray *array = [[NSMutableArray alloc] init];
FILE *file = popen([[[#"osascript -e \"" stringByAppendingString:execScript] stringByAppendingString:#"\" 2>&1"] UTF8String], "r");
while (getline(&pointer, &buffer_size, file) != -1)
[array addObject:[NSString stringWithUTF8String:pointer]];
char *error = (char *)[[array componentsJoinedByString:#""] UTF8String];
if (strlen(error) > 0 && error[strlen(error) - 1] == '\n')
error[strlen(error) - 1] = '\0';
if ([[NSString stringWithUTF8String:error] isEqualToString:#""])
success = true;
[array release];
free(pointer);
pclose(file);
break;
}
}
}
}
}
}
CFRelease(windowArray);
return success;
}
The code it is based on does not work as advertised for its original purpose. Although, it did help me a lot to get working all the stuff I needed to answer this question. The code my answer is based on can be found here.

How to solve HackerRank problems in Objective-C

Can anybody explain how to give the hacker rank test in objective-C. Specially the part "Read input from STDIN. Print output to STDOUT"
How to read input and out in objective-c ?
What i have got so far is get input like
NSFileHandle *fileHandler = [NSFileHandle fileHandleWithStandardInput];
NSData *inputData = [fileHandler availableData];
NSString *inputString = [[NSString alloc] initWithData:inputData encoding:NSUTF8StringEncoding];
But to print output, following does not print anything on HackerRank console (but works flawlessly on Xcode console)
NSFileHandle* fileHandler=[NSFileHandle fileHandleWithStandardOutput];
[fileHandler writeData: [formattedString dataUsingEncoding: NSNEXTSTEPStringEncoding]];
The simplest possible way to "Read input from STDIN. Print output to STDOUT" would be to use scanf and printf.
Here's a sample template to get you started:
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
int count;
scanf("%d", &count);
NSMutableArray *inputIntegers = [NSMutableArray new];
for (int i=0; i<count; i++) {
int inputElement;
scanf("%d", &inputElement);
[inputIntegers addObject:[NSNumber numberWithInt:inputElement]];
}
//to print a specific element:
printf("printing element 0: %d", (int)[inputIntegers[0] integerValue]);
[pool drain];
return 0;
}
Before you take a shot at this journey, a few things:
Make sure ARC is disabled (search for CLANG_ENABLE_OBJC_ARC in build settings, and set it to NO)
Avoid using self. This is functional programming.
Use C functions, not Objective-C methods, meaning, use
instead of
- (NSInteger)sumOfNumbers : (NSInteger)a and:(NSInteger)b {
return a + b;
}
use
int sumOfNumbers(int a, int b){
return a + b;
}
Happy Programming.
Having just been handed one of these tests, I opted to get out of main.m immediately and into Objective-C like so:
#import <Foundation/Foundation.h>
//Objective-C helper class to take over from main.m
//.h
#interface MainClass : NSObject
+ (BOOL)startMain;
#end
//.m
#implementation MainClass
+ (BOOL)startMain {
//Read the STDIN here using the Objective-C wrapper methods
NSInteger n = [self readInt];
[self printInt:n];
NSArray *numbers = [self readIntArrayOfLength:n];
[self printIntNumberArray:numbers];
return YES;
}
+ (NSInteger)readInt {
int n;
scanf("%i",&n);
return n;
}
+ (NSArray *)readIntArrayOfLength:(NSInteger)len {
NSMutableArray *result = [NSMutableArray array];
for (int i =0; i < len; i++) {
[result addObject:[NSNumber numberWithInt:[self readInt]]];
}
return [result copy];
}
//Helpers to print an int and array of ints to STDOUT
+ (void)printInt:(NSInteger)i {
printf("%li\n",(long)i);
}
+ (void)printIntNumberArray:(NSArray *)array {
printf("[");
[array enumerateObjectsUsingBlock:^(NSNumber *n, NSUInteger idx, BOOL * _Nonnull stop) {
printf("%li",(long)[n integerValue]);
if (idx < array.count-1) {
printf(",");
}
}];
printf("]\n");
}
#end
//This is what will actually run when you hit "Run Code"
int main(int argc, char * argv[]) {
#autoreleasepool {
return [MainClass startMain];
}
}
Now you can do whatever you like from here using Objective-C.
So in this example a sample input of:
3
11 2 4
Would produce this output:
3
[11,2,4]
Not useful in of itself but illustrates the successful read.
It's a lot simpler in Swift, but here's code to accomplish the same thing anyway:
func readInt() -> Int? {
if let ln = readLine() {
return Int(ln)
}
return nil
}
func readIntArray() -> [Int]? {
if let ln = readLine() {
return ln.characters.split(" ").filter({ Int(String($0)) != nil }).map({ Int(String($0))! })
}
return nil
}
let n = readInt()!
let array = readIntArray()!
print(n)
print(array)
The functions return optionals because even though you are going to force-unwrap the input, better the crash for a nil optional happens in your code than the boilerplate.
#import <Foundation/Foundation.h>
int sum(int a, int b) {
return a + b;
}
int main() {
#autoreleasepool {
int T;
int A;
int B;
printf("Enter number of test cases: ");
scanf("%d", &T);
for (int i=0; i < T; i++) {
scanf("%d", &A);
scanf("%d", &B);
printf("%d\n", sum(A,B));
}
}
return 0;
}
That ought to do it.
Your question is really too general for SO, do not be surprised if it gets closed soon. You need in general to ask specific questions, show what you've tried, etc. But if you're just after a few hints to get you going...
You don't say whether you are a programmer already or know Objective-C in particular, assuming both:
In Xcode look at the Command Line Tool project type
Look into NSFileHandle and its methods, e.g. fileHandleWithStandardInput
Note you can also use the C stdio functions, converting C-style to Objective-C styles strings etc. as needed.
I created github repo with some hackerrank problem solutions written in objective-c. It is on the beginning stage, feel free to contribute by adding your solutions as well.
HackerRank for Objective-C
Since Objective-C is a superset of C, you can use C methods for reading and printing out:
NSInteger n;
char *input[25];
NSMutableArray *strings = [NSMutableArray array];
NSString *s;
NSString *temp;
scanf("%lu", &n);
for (NSInteger i = 0; i < n; ++i) {
scanf("%s", input);
s = [NSString stringWithUTF8String:input];
[inputs addObject:s];
}
If n is of type int, you can read it as:
scanf("%d", &n);

Thread 1: signal sigabrt error

Why do I get the thread error on the NSLog(#"%#", numbers[i]); line?
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
#autoreleasepool {
NSMutableArray *numbers = [NSMutableArray array];
int i;
//Create an arry with the number 0-9
for (i = 0; i < 10; ++i) {
numbers[i] = #(i);
//Sequence through the array and display the values
for (i = 0; i < 10; ++i) {
NSLog(#"%#", numbers[i]);
//Look how NSLog can display it with a singe %# format
NSLog(#"====== Using a single NSLog");
NSLog(#"%#", numbers);
}
}
}
return 0;
}
You're receiving an exception because you have your two for loops nested, and the inner one is trying to iterate through ten values in numbers array, but trying to do that before you've done populating the array in the outer loop.
I presume you do not want those for loops nested:
NSMutableArray *numbers = [NSMutableArray array];
int i;
//Create an array with the number 0-9
for (i = 0; i < 10; ++i)
numbers[i] = #(i);
//Sequence through the array and display the values
for (i = 0; i < 10; ++i)
NSLog(#"%#", numbers[i]);
//Look how NSLog can display it with a single %# format
NSLog(#"====== Using a single NSLog");
NSLog(#"%#", numbers);

Objective C Pointers

I am experiencing a very odd problem with pointers. As you could see from the below code, I am using a method that generates a random 4 by 4 character grid. It return a pointer to a two dimensional character array. The problem is that when i try to assign the returned pointer to another pointer and try to print the generated grid, I get just one strange symbol.
Header File
#import <Foundation/Foundation.h>
#interface GridGenerator : NSObject
{
}
-(char (*)[4]) generateGrid;
-(int (*)[2]) bbb;
-(void) print;
#end
Implementation File
#import "GridGenerator.h"
#implementation GridGenerator
-(char (*)[4])generateGrid{
char vowels[6] = {'A','E','I','O','U','Y'};
char consonants[20] = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Z'};
char grid[4][4];
int vowelsLength = (sizeof vowels / sizeof vowels[0]);
int consLength = (sizeof consonants / sizeof consonants[0]);
int gridSize = (sizeof grid / sizeof grid[0]);
for(int i=0;i<gridSize;i++){
int vowelsInGridRow = 0;
int noOfVowels = (arc4random() % 2) + 1;
for(int j=0;j<gridSize;j++){
if(noOfVowels != vowelsInGridRow){
int vowIndex = arc4random() % vowelsLength;
char s = vowels[vowIndex];
grid[i][j] = s;
vowelsInGridRow++;
}
else{
int consIndex = arc4random() % consLength;
char s = consonants[consIndex];
grid[i][j] = s;
}
}
}
char (*sd)[4]= grid;
return sd;
}
-(void)print{
char (*grid)[4] = [self generateGrid];
NSString *s = #"\n";
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
s = [s stringByAppendingString:[NSString stringWithFormat:#"%c",grid[i][j]]];
}
s = [s stringByAppendingString:#"\n"];
}
NSLog(#"%#",s);
}
Main File(Test)
#import <Foundation/Foundation.h>
#import "Crossword.h"
#import "GridGenerator.h"
int main(int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
GridGenerator *gen = [[GridGenerator alloc] init];
[gen print];
[pool release];
return 0;
}
When I run the code, you can see the result below. After the 'U' there is an inverted question mark(could not be pasted here).
2013-06-02 11:24:29.923 CrosswordTest[646:303]
U
Do you have an idea, what could causes this to happen? I am struggling already for several hours and I cannot find any explanation.
You are returning a reference to a temporary. Explosion (undefined behavior) should be expected.
Workaround. Create a structure:
typedef struct {char at[4][4];} t_grid;
Then populate and return the t_grid by value:
- (t_grid)generateGrid
{
char vowels[6] = {'A','E','I','O','U','Y'};
char consonants[20] = {'B','C','D','F','G','H','J','K','L','M','N','P','Q','R','S','T','V','W','X','Z'};
t_grid grid;
...
int gridSize = (sizeof grid.at / sizeof grid.at[0]);
...
grid.at[i][j] = s;
...
return grid;
}
- (void)print
{
t_grid grid = [self generateGrid];
...
Note that you should not use this approach for large arrays or variable length arrays. 4*4 octets is small.