Что описывает Делегата Приложения лучше всего? Как это вписывается в целое понятие?

В вашей программе есть несколько проблем

1) С помощью

scanf ("%[^;]s", inputString);
gets(inputString);

вы переписываете inputString с получением после scanf , Например, если вход foo bar loop;, вы устанавливаете inputString с foo bar loop, затем вы устанавливаете его снова с ;, так что вы потеряли все, что получили, с scanf

[1129 ] 2) Оба scanf и получают могут записывать из inputString , у вас нет никакой защиты, максимальный размер для чтения может быть предоставлен scanf и вы можете заменить использование gets на fgets (забывая тот факт, что вы переписали в inputString )

3) вы никогда не принимайте во внимание случай EOF, всегда предполагая, что что-то есть, введите

4) В

    if(inputString[i]==ch)
    {
        outputString[j]=inputString[i+1];
        i++;
    }
    else
    {
        outputString[j]=inputString[i];
    }
    j++;

outputString[j]=inputString[i+1]; предполагается, что вам никогда не придется два раза подряд убирать символ, таким образом сделать неправильно.

5) Использовать фиксированный размер массива не обязательно, выделяйте массив, затем realloc при необходимости

6) В

for (i=0;i<j;i++)
{
    printf ("%c", outputString[i]);
}

лучше заканчивать ] outputString с нулевым символом для простой печати с помощью fputs или помещает для добавления финала \ n в случае, если он отсутствует


Здесь предложение:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
  char * inputString = NULL;
  size_t sz = 0, used = 0;
  int v;

  printf ("Enter a multi line string (ended by ';'):\n");

  while ((v = getchar()) != ';') {
    if (v == EOF) {
      puts("premature EOF, abort");
      return -1;
    }

    if (used == sz) {
      sz += 100;
      inputString = realloc(inputString, sz);
      if (inputString == NULL) {
        puts("not enough memory");
        return -1;
      }
    }
    inputString[used++] = v;
  }

  /* read up to end of line */
  char * outputString = 0;

  if (getline(&outputString, &sz, stdin) == -1) {
    puts("premature EOF or not enough memory");
    return -1;
  }
  free(outputString);

  printf ("Enter a letter to be removed:\n");

  char ch;

  if (scanf ("%c", &ch) != 1) {
     puts("premature EOF, abort");
     return -1;
  }

  size_t i, j = 0;

  outputString = malloc(used + 1); /* worst case, +1 to have place for null character */

  for (i = 0; i != used; ++i)
  {
    if (inputString[i] != ch)
      outputString[j++] = inputString[i];
  }
  outputString[j] = 0;

  puts(outputString);

  free(inputString);
  free(outputString);

  return 0;
}

Компиляция и исполнение:

pi@raspberrypi:/tmp $ gcc -pedantic -Wextra -g l.c
pi@raspberrypi:/tmp $ ./a.out
Enter a multi line string (ended by ';'):
this is a paragraph
  terminated by
a ;!!
Enter a letter to be removed:
i
ths s a paragraph
  termnated by
a 

Исполнение по valgrind :

pi@raspberrypi:/tmp $ valgrind ./a.out
==3900== Memcheck, a memory error detector
==3900== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3900== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3900== Command: ./a.out
==3900== 
Enter a multi line string (ended by ';'):
this is a paragraph
  terminated by
a ;!!
Enter a letter to be removed:
i
ths s a paragraph
  termnated by
a 
==3900== 
==3900== HEAP SUMMARY:
==3900==     in use at exit: 0 bytes in 0 blocks
==3900==   total heap usage: 5 allocs, 5 frees, 2,307 bytes allocated
==3900== 
==3900== All heap blocks were freed -- no leaks are possible
==3900== 
==3900== For counts of detected and suppressed errors, rerun with: -v
==3900== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 6 from 3)
16
задан Honey 1 May 2018 в 01:34
поделиться

2 ответа

In Cocoa, a delegate is an object that another object defers to on questions of behavior and informs about changes in its state. For instance, a UITableViewDelegate is responsible for answering questions about how the UITableView should behave when selections are made or rows are reordered. It is the object that the UITableView asks when it wants to know how high a particular row should be. In the Model-View-Controller paradigm, delegates are Controllers, and many delegates' names end in "Controller."

At risk of stating the obvious, the UIApplicationDelegate is the delegate for the UIApplication. The relationship is a bit more obvious in Cocoa (Mac) than in Cocoa Touch (iPhone), since the NSApplication delegate is able to control the NSApplication's behavior more directly (preventing the application from terminating for instance). iPhone doesn't permit much control over the UIApplication, so mostly the UIApplicationDelegate is informed of changes rather than having an active decision-making process.

The UIApplicationDelegate isn't strictly available from everywhere in the app. The singleton UIApplication is ([UIApplication sharedApplication]), and through it you can find its delegate. But this does not mean that it's appropriate for every object in an app to talk directly to the app delegate. In general, I discourage developers from having random objects talk to the app delegate. Most problems that are solved that way are better solved through Singletons, NSNotification, or other delegate objects.

As to its creation, on Mac there is nothing magical about the app delegate. It's just an object instantiated and wired by the NIB in most cases. On iPhone, however, the app delegate can be slightly magical if instantiated by UIApplicationMain(). The fourth parameter is an NSString indicating the app delegate's class, and UIApplicationMain() will create one and set it as the delegate of the sharedApplication. This allows you to set the delegate without a NIB (something very difficult on Mac). If the fourth parameter to UIApplicationMain() is nil (as it is in the Apple templates), then the delegate is created and wired by the main NIB, just like the main window.

37
ответ дан 30 November 2019 в 16:25
поделиться

Объект создается таким образом;

Функция main ищет основной наконечник, установленный в info.plist. Перо имеет в качестве делегата приложения, который установлен на некоторый класс, который должен реализовывать UIApplicationDelegates и его необходимые методы. Затем делегат приложения загружает некоторый viewcontroller.

Он служит объектом обратного вызова всего приложения для событий, влияющих на все приложение, таких как нехватка памяти и т. Д.

3
ответ дан 30 November 2019 в 16:25
поделиться
Другие вопросы по тегам:

Похожие вопросы: